You can use Popen()
and .communicate()
instead of call()
. I am not completely sure why call()
does not work in your case, but the following would work -
program1.py
import subprocess
import sys
inputfile = open('input.txt', 'r')
inputfile.readline()
inputfile.readline()
p = subprocess.call(['python', 'program2.py'],stdin=subprocess.PIPE,stdout=sys.stdout)
p.communicate(inputfile.read())
inputfile.close()
.decode()
is needed as communicate()
expects byte string, not normal string. I also redirected the stdout
for the process to the stdout
of your script, so that the results are printed. Also, a better way to write program2.py
is -
import sys
for l in sys.stdin:
print l
This does not cause program2.py
to go into infinite loop.
Example/Demo -
I have two files, a.py
and b.py
-
a.py -
import subprocess
import sys
inputfile = open('input.txt', 'r')
inputfile.readline()
inputfile.readline()
p = subprocess.Popen(['/usr/bin/python', 'b.py'],stdin=subprocess.PIPE,stdout=sys.stdout)
p.communicate(inputfile.read())
inputfile.close()
b.py -
import sys
for l in sys.stdin:
print l
Result of running a.py
-
3
4