【问题标题】:Reading Multiple lines in stdin using subprocess使用子进程在标准输入中读取多行
【发布时间】:2013-02-20 09:59:05
【问题描述】:

我正在尝试从 python 运行一个 c++ 程序。我的问题是每次我跑步:

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

它只读取文件的第一行。每次我用一个while循环将它括起来时,它都会因为无限循环而崩溃。有没有其他方法可以读取testcases.txt 中的所有行?

我的示例代码如下:

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()

【问题讨论】:

  • 只是检查一下,您是想多次调用 sampleprog.exe,基本上在文件中的每一行调用一次,还是想将文件中的所有行作为输入调用一次?
  • 实际上我想每行调用一次多次,因为我认为将文件中的所有行作为输入调用一次将取决于用户传递的内容?

标签: python subprocess stdin


【解决方案1】:

读取文件中所有行的最佳方法,假设您想逐行读取,并且只将当前行传递给程序是

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

someFile.readlines() 读取并返回 someFile 中所有行的列表。但是,您需要将其传递给 sampleprog.exe。我会使用 Popen.communicate() 。可能这是一个巨大的矫枉过正,但你的循环看起来像

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

另外,您应该打开 saveFile 进行写入('w'rite 或 'a'pend 选项)

【讨论】:

  • ahhh 是的,我认为这肯定是一个巨大的杀戮,但无论如何,它有效.. 我没有考虑将通信作为一种解决方案,因为我专注于 execfile(),它实际上不起作用,因为非 ASCII 字符,但现在我回到了正轨,我会尝试为此创建一个沙箱。再次感谢
【解决方案2】:

您正在向 Popen 传递一个打开以作为标准输出读取的文件。我认为输出应该是这样构造的:

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

【讨论】:

  • 好的,tnx,我去看看
猜你喜欢
  • 1970-01-01
  • 2011-02-17
  • 2019-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多