1

I'm trying to do something like the following to print 3 and 4:

input.txt

1
2
3
4

program1.py

import subprocess
inputfile = open('input.txt', 'r')
inputfile.readline()
inputfile.readline()
subprocess.call('python program2.py',stdin=inputfile)
inputfile.close()

program2.py

while True:
    print raw_input() 

It will print nothing. But if I remove the readlines() it will print 1 through 4 just fine.

How can I use a file starting at a certain line for a stdin for a subprocess?

Val
  • 13
  • 3
  • I believe the answer provided here http://stackoverflow.com/questions/8475290/how-do-i-write-to-a-python-subprocess-stdin should solve the problem. – Coding Orange Aug 04 '15 at 19:20

1 Answers1

0

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
Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176