Interact with an interactive shell script on python
Asked Answered
L

2

6

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?

Lavery answered 17/2, 2016 at 13:22 Comment(2)
You may want to look what subprocess.PIPE meansDive
How do you use the stdin/stdout? The documentation says: Warning Use communicate() rather than .stdin.write, .stdout.read or .stderr.read to avoid deadlocks due to any of the other OS pipe buffers filling up and blocking the child process.Paulo
D
3

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.

Dishonest answered 17/2, 2016 at 13:31 Comment(0)
C
2

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.

Canaille answered 17/2, 2016 at 13:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.