The title to this may be confusing, but basically I want to be able to do the following:
import subprocess
subprocess.call(["python"])
subprocess.call(["import", "antigravity"])
subprocess.check_call(["print","\"This is so meta\" "])
subprocess.call(["exit()"])
Expected behavior would be that it would open up a python terminal session, then open up xkcd comic 353, print 'this is so meta' to the command line, and finally exit the python command line.
Basically, I want to be able to open a python session, and run commands in it from my python script. I also want to be able to check the output of commands I run in the script. Is this possible? and if so, what library do I need to be using? Will subprocess do this?
Something like this...
import subprocess
proc = subprocess.Popen(
'python',stdout=subprocess.PIPE,
stdin=subprocess.PIPE)
proc.stdin.write('import antigravity\n')
proc.stdin.write('print "something"\n')
proc.stdin.close()
result = proc.stdout.read()
print result
So we're creating a process and telling it that input will come from stdin (like someone typing). We then write anything we like to that and read the response from stdout (what would normally be printed to the screen)
If you need to communicate with process you should use communicate()
method instead stdin.write()
otherwise you can find some no desirable effects.
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.
Source: http://docs.python.org/2/library/subprocess.html#popen-objects
from subprocess import PIPE, STDOUT, Popen
e = Popen(["/usr/local/bin/python3"], stdout = PIPE, stdin = PIPE, stderr = STDOUT, shell = False)
out, err = e.communicate(b"""
import sys
print('Interactive python version: %s' % str(sys.version))
sys.exit(4)
""")
e.wait()
print ('Exit code', e.returncode)
print ('Output', out)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With