Cannot start two interactive shells using popen

前端 未结 2 1971
攒了一身酷
攒了一身酷 2021-01-21 11:50

I have the following Python snippet, and cannot explain why it behaves the way it does.

import subprocess  
bash1 = subprocess.Popen([\"/bin/bash\",\"-l\", \"-i\         


        
2条回答
  •  一生所求
    2021-01-21 12:01

    Answer to question 1:

    This is because an interactive bash shell expects to be attached to a terminal (the 'controlling terminal') and acquire it in order to process job control interrupts (e.g. Control-Z). The second invocation tries to acquire the terminal but can't, so gets temporarily suspended.

    Answer to question 2:

    communicate writes its argument to the stdin pipe of the child process and then closes it. Bash terminates when its stdin is exhausted (it is like entering Control-D in a bash terminal session).

    If you want to keep the bash child process running, then write to its stdin directly rather than use communicate as follows:

    bash1.stdin.write("echo 'works1'\n")
    

    You do need to add the newline if you want the command to actually execute, by the way.

    A solution:

    If you want to run two or more interactive shells, you should setup the stdin of each shell to be a pseudo-terminal rather than a subprocess PIPE.

提交回复
热议问题