8

我遇到的问题如下,我会用简单的例子来说明。我编写了一个需要用户交互的 python 脚本,特别是它使用 raw_input() 函数来获取用户的输入。下面的代码只是要求用户连续输入两个数字(在每个数字之间按回车键),然后返回答案(惊喜,惊喜,它被称为“sum_two_numbers.py”)。哼哼!

#! /usr/bin/python

#  -------------------
#  sum_two_numbers.py
#  -------------------
#  This script asks the user for two numbers and returns the sum!

a = float(raw_input("Enter the first number:"))
b = float(raw_input("Enter the second number:"))

print a+b

现在,我想编写一个单独的 python 脚本来执行上述脚本并将两个必要的数字“提供”给它。因此,我将此脚本称为“feeder.py”。我尝试使用 Python 的“子进程”模块编写此脚本,特别是使用“Popen”类及其相关的“通信”方法。下面是尝试输入数字“5”和“4”的脚本。

#! /usr/bin/python

#  ----------
#  feeder.py
#  ----------
import subprocess

child = subprocess.Popen("./sum_two_numbers.py",stdin=subprocess.PIPE)

child.communicate("5")
child.communicate("4")

此代码不起作用,并在执行时返回错误:

$ ./feeder.py
Enter the first number:Enter the second number:Traceback (most recent call last):
  File "./sum_two_numbers.py", line 6, in <module>
    b = float(raw_input("Enter the second number:"))
EOFError: EOF when reading a line
Traceback (most recent call last):
  File "./feeder.py", line 8, in <module>
    child.communicate("4")
  File "/usr/lib/python2.7/subprocess.py", line 740, in communicate
    self.stdin.write(input)
ValueError: I/O operation on closed file

我不知道如何编写“feeder.py”以便它可以做我想做的事情,这些错误一直在阻碍我。我怀疑由于文档中的以下注释而出现此错误:

Popen.communicate(输入=无)

与进程交互:将数据发送到标准输入。从 stdout 和 stderr 读取数据,直到到达文件结尾。等待进程终止。

我不知道如何理解这句话,以及它如何帮助我......

谁能帮助我使上述脚本正常工作,即如何正确使用 subprocess 和 Popen ... 我已经尝试过 Pexpect,Expect 但遇到了诸如不输出子代码的输入请求之类的问题,而我通常不知道它在做什么。

4

1 回答 1

9

您只能调用communicate一次。因此,您需要一次传递所有输入,即child.communicate("1\n1\n"). 或者,您可以写入标准输入:

child = subprocess.Popen("./test.py", stdin=subprocess.PIPE)         

child.stdin.write("1\n")                                                       
child.stdin.write("1\n")
于 2012-10-19T21:12:46.507 回答