简体   繁体   English

使用子过程在stdin中读取多行

[英]Reading Multiple lines in stdin using subprocess

I am trying to run a c++ program from python. 我正在尝试从python运行c ++程序。 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. 每次我用while循环将其包围时,由于无限循环,它最终都会崩溃。 Is there any other way to read all the lines inside the testcases.txt ? 还有其他方法可以读取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. someFile.readlines()读取并返回someFile中所有行的列表。 However, you need it to be passed to sampleprog.exe. 但是,您需要将其传递给sampleprog.exe。 I would use Popen.communicate() for it. 我将使用Popen.communicate()。 Probably it's an giant overkill, but then your loop would look like 可能这是一个巨大的矫kill过正,但随后您的循环看起来像

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) 另外,您应该打开saveFile进行写入(“ w'rite”或“ a” ppend选项)

You are passing to Popen a file opened for reading as stdout. 您正在传递给Popen一个打开的文件,以stdout的形式读取。 I think the output should be constructed like this: 我认为输出应该这样构造:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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