You probably wanna use Popen.communicate(input=None, timeout=None) and set the shell arg to true. Then you wanna wait on the process output stream for the response to your command. Note: Popen.communicate requires the input to be byte-encoded. The output of Popen.communicate is also byte encoded, so you need to do a str.decode() on it to extract the encoded strings.
All of this is fully documented in the Python API. I would suggest you read the manual.
Or, you could use a library like this one which wraps all of this stuff for you.
import subprocess
proc = subprocess.Popen('ls', stdout=subprocess.PIPE, stdin=subprocess.PIPE)
try:
outs, errs = proc.communicate(timeout=15) # use input= param if you need to
proc.wait()
except TimeoutExpired:
proc.kill()
outs, errs = proc.communicate()
print ('%s, %s' % (outs, errs))
Output and comparison to actual 'ls' output:
$ python popen_ex.py
b'__pycache__\npopen_ex.py\n', None
$ ls
__pycache__ popen_ex.py
Any additional commands you need to send to popen can be sent in proc.communicate.
If you REALLY want to communicate to an interactive shell, Popen.communicate() allows for a ONE TIME write to stdin and read from stdout/stderr. After one call to Popen.communicate(), the input/output/error streams are closed by subprocess. IF YOU WANT A FULLY INTERACTIVE SHELL, you MUST either write one yourself, or use a library, like the one I linked.
import subprocess
proc = subprocess.Popen('sh', stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
try:
outs, errs = proc.communicate(input='ls'.encode('ascii'), timeout=15)
proc.wait()
print ('%s, %s' % (outs, errs))
proc = subprocess.Popen('sh', stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
outs, errs = proc.communicate(input='ps'.encode('ascii'), timeout=15)
proc.wait()
print ('%s, %s' % (outs, errs))
except TimeoutError:
proc.kill()
outs, errs = proc.communicate()
Output and comparison to actual 'ls', 'ps'
$ python popen_ex.py
b'__pycache__\npopen_ex.py\n', b''
b' PID TTY TIME CMD\n 879 ttys000 0:00.18 -bash\n 7063 ttys000 0:00.06 python popen_ex.py\n 7066 ttys000 0:00.00 sh\n 911 ttys001 0:00.06 -bash\n 938 ttys002 0:00.16 -bash\n 6728 ttys002 0:00.11 python\n 972 ttys004 0:00.06 -bash\n 1019 ttys005 0:00.06 -bash\n 1021 ttys006 0:00.06 -bash\n 1023 ttys007 0:00.06 -bash\n', b''
$ ls
__pycache__ popen_ex.py
$ ps
PID TTY TIME CMD
879 ttys000 0:00.19 -bash
911 ttys001 0:00.06 -bash
938 ttys002 0:00.16 -bash
6728 ttys002 0:00.11 python
972 ttys004 0:00.06 -bash
1019 ttys005 0:00.06 -bash
1021 ttys006 0:00.06 -bash
1023 ttys007 0:00.06 -bash