我遇到的问题如下,我会用简单的例子来说明。我写了一个需要用户交互的 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 的“subprocess”编写此脚本' 模块,特别是使用 'Popen' 类及其关联的 'communicate' 方法。下面是尝试输入数字“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(input=None)
Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate.
我不确定如何理解这句话,以及它如何帮助我...
任何人都可以帮助我使上述脚本工作,即如何正确使用 subprocess 和 Popen ......我已经尝试过 Pexpect,Expect 但遇到了一些问题,比如它没有输出子代码的输入请求,而且我通常不知道它在做什么。
最佳答案
您只能调用一次communicate
。因此,您需要一次传递所有输入,即 child.communicate("1\n1\n")
。或者,您可以写入标准输入:
child = subprocess.Popen("./test.py", stdin=subprocess.PIPE)
child.stdin.write("1\n")
child.stdin.write("1\n")
关于python - 在一个脚本中使用 Python 的子进程和 Popen 来运行另一个需要用户交互的 Python 脚本(通过 raw_input),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12980148/