简体   繁体   中英

Reading Multiple lines in stdin using subprocess

I am trying to run a c++ program from python. My problem is that everytime i run:

subprocess.Popen(['sampleprog.exe'], stdin = iterate, stdout = myFile)

it only reads the first line in the file. Every time I enclose it with a while loop it ends up crushing because of the infinite loop. Is there any other way to read all the lines inside the testcases.txt ?

My Sample Code below:

someFile = open("testcases.txt","r")
saveFile = open("store.txt", "r+")

try:
    with someFile as iterate:
        while iterate is not False:
            subprocess.Popen(['sampleprog.exe'],stdin = iterate,stdout = saveFile)

except EOFError:
    someFile.close()
    saveFile.close()
    sys.exit()

The best way to read all lines inside the file, assuming You want read it line by line, and pass only current line to program is

with open("testcases.txt","r") as someFile:
    iterate = someFile.readlines()
    for line in iterate:
        #Code

someFile.readlines() reads and returns the list of all lines in someFile. However, you need it to be passed to sampleprog.exe. I would use Popen.communicate() for it. Probably it's an giant overkill, but then your loop would look like

for line in iterate:
    s = subprocess.Popen(['sampleprog.exe'], stdin = subprocess.PIPE, stdout = saveFile)
    s.communicate(line)

Also, You should open saveFile for writing ('w'rite or 'a'ppend options)

You are passing to Popen a file opened for reading as stdout. I think the output should be constructed like this:

 saveFile = open("store.txt", "w")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM