Interact with an interactive shell script on python

5.5k Views Asked by At

I have an interactive shell application on windows. I would like to write a python script that will send commands to that shell application and read back responses. However i want to do it interactively, i.e. i want the shell application to keep running as long the python script is.

I have tried

self.m_process subprocess.Popen(path_to_shell_app,shell=True,stdin=subprocess.PIPE,stdout=subprocess.PIPE,universal_newlines=True)

and then using stdin and stdout to send and recieve data. it seems that the shell application is being opened but i can't communicate with it.

what am i doing wrong?

2

There are 2 best solutions below

0
On

Next you should use communicate

stdout, stderr = self.m_process.communicate(input=your_input_here)

From the subprocess module documentation

Popen.communicate(input=None)
Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate. The optional input argument should be a string to be sent to the child process, or None, if no data should be sent to the child.

communicate() returns a tuple (stdoutdata, stderrdata).

Note that if you want to send data to the process’s stdin, you need to create the Popen object with stdin=PIPE. Similarly, to get anything other than None in the result tuple, you need to give stdout=PIPE and/or stderr=PIPE too.

0
On

There is a module that was built just for that: pexpect. To use, import pexpect, and then use process = pexpect.spawn(myprogram) to create new subprocesses, and use process.expect(mystring) or process.expect_exact(mystring) to search for prompts, or to get responses. process.send(myinput) and process.sendline(myinput) are used for sending information to the subprocess.