I'm trying to understand how Python's subprocess module works and have begun by setting myself some problems that weren't as simple as I thought. Specifically, I'm trying to interact with a Python intepreter that has been created as a subprocess.
I've created a test module, dummy.py
that is structured as follows:
def hi():
print "Hi Earth"
hi()
Then, to test my ability to use the subprocess module, I've written a module called pyrun.py
, that is structured as follows:
import subprocess
def subprocess_cmd1():
outFile = open("tempy1.tmp",'w')
proc = subprocess.Popen("pwd", stdin=subprocess.PIPE, stdout=outFile, stderr=outFile, shell=True)
outFile.close()
def subprocess_cmd2():
outFile = open("tempy2.tmp",'w')
proc = subprocess.Popen('python dummy.py', stdin=subprocess.PIPE, stdout=outFile, stderr=outFile, shell=True)
outFile.close()
def subprocess_cmd3():
outFile = open("tempy3.tmp",'w')
proc = subprocess.Popen('python', stdin=subprocess.PIPE, stdout=outFile, stderr=outFile, shell=True)
proc.communicate('import dummy')
outFile.close()
def subprocess_cmd4():
outFile = open("tempy4.tmp",'w')
proc = subprocess.Popen('python', stdin=subprocess.PIPE, stdout=outFile, stderr=outFile, shell=True)
proc.communicate('import dummy')
proc.communicate('dummy.hi()')
outFile.close()
print "Start"
subprocess_cmd1()
subprocess_cmd2()
subprocess_cmd3()
subprocess_cmd4()
print "Stop"
The idea is to send input to the subprocess from the calling process and to have all output sent to a text file.
When I attempt to run pyrun from the command line, I get the following results:
me@Bedrock1:~/Projects/LushProjects/newCode$ python pyrun.py
Start
Traceback (most recent call last):
File "pyrun.py", line 42, in <module>
subprocess_cmd4()
File "pyrun.py", line 35, in subprocess_cmd4
proc.communicate('dummy.hi()')
File "/usr/lib/python2.7/subprocess.py", line 785, in communicate
self.stdin.write(input)
ValueError: I/O operation on closed file
subprocess_cmd1 - 3
run without crashing. The error comes in subprocess_cmd4()
, when trying to execute the statement:
proc.communicate('dummy.hi()')
This seems to be because the communicate
method closes the pipe to stdin
after it's first used. Why does it do that? Is there any advantage to assuming the pipe should close?
Also, when I look at the contents of tempy3.tmp
(my output file for subprocess_cmd3
), it's missing the 'start' text of the Python interpreter - i.e.
Python 2.7.6 (default, Mar 22 2014, 22:59:56)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
Why is that? I redirected both stdout
& stderr
to outFile
.
Finally, why is tempy4.tmp
completely empty? Shouldn't it contain, at least, the text that was sent to it before it crashed? (i.e. it should look a lot like tempy3.tmp
)