Persistent Terminal Session in Python

I may not understand this correctly at all, but I'm trying to allow a Python program to interact with a subprocess that runs commands like in the Linux shell.

For example, I want to be able to run "cd /" and then "pwd later in the program and get" / ".

I'm currently trying to use subprocess.Popen and the communication () method to send and receive data. The first command sent using the Popen constructor works fine and gives the correct output. But I can not send another command via communication (input = "pwd").

My code is:

from subprocess i term=Popen("pwd", stdout=PIPE, stdin=PIPE) print(flush(term.communicate())) term.communicate(input="cd /") print(flush(term.communicate(input="pwd"))) 

Is there a better way to do this? Thanks.

Also, I am running Python 3.

+4
source share
1 answer

First of all, you need to understand that running a shell command and running a program are not the same thing.

Let me give an example:

 >>> import subprocess >>> subprocess.call(['/bin/echo', '$HOME']) $HOME 0 >>> subprocess.call(['/bin/echo $HOME'], shell=True) /home/kkinder 0 

Note that without the shell = True parameter, the text $HOME does not expand. This is because the /bin/echo program does not parse $HOME , Bash does. What really happens in the second call is something similar:

 >>> subprocess.call(['/bin/bash', '-c', '/bin/echo $HOME']) /home/kkinder 0 

Using the shell=True parameter, basically tells the subprocess module, move on to interpreting this text with the shell.

So, you can add shell=True , but then the problem is that as soon as the command ends, its state will be lost. Each application on the stack has its own working directory. So the directory will look something like this:

  • bash - / foo / bar
    • python - / foo
      • bash through a subprocess - /

After executing your command, the python process path remains the same, and the subprocess path is discarded after the shell completes with the command.

In principle, what you are asking for is not practical. What you will need to do is open the channel to Bash, interactively submit it, pointing to user types, and then read the output in a non-blocking way. This will be associated with a complex pipe, flows, etc. Are you sure there is no better way?

0
source

All Articles