如何在两个python脚本之间进行通信?

2024-05-16 20:23:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个3d party python脚本,它从命令行获取输入。此脚本(input.py)中的相关代码如下所示:

import sys

def chooseinput():
    valid_inputs = ('a', 'b')
    inp = raw_input('Enter choice (%s): ' % "/".join(valid_inputs))
    if inp not in valid_inputs:
        sys.stderr.write("Unsupported input %s\n" % inp)
        return
    print 'You chose ' + '\'' + inp + '\''
    return inp

if __name__ == "__main__":
    chooseinput()
    # do something with the input...
    chooseinput()
    # do something with the input...

我正试图编写另一个python脚本(harness.py)来生成上述脚本的输入。

import subprocess

def harness():
    p = subprocess.Popen(['python', 'input.py'], stdin=subprocess.PIPE)
    p.stdin.write('a')
    p.stdin.write('b')

if __name__ == '__main__':
    harness()

在命令行中,我运行:

$ python harness.py
Enter choice (a/b): Enter choice (a/b): Traceback (most recent call last):
  File "input.py", line 13, in <module>
    chooseinput()
  File "input.py", line 5, in chooseinput
    inp = raw_input('Enter choice (%s): ' % "/".join(valid_inputs))
EOFError: EOF when reading a line

如果第一个脚本中只有一个输入,那么可以通过删除第二个write调用使第二个脚本工作。如果第一个脚本需要多个输入,则会出现上述错误。


Tags: inpy脚本inputifstdinwriteharness
3条回答

你应该去Pexpect看看。

Pexpect是一个纯Python模块,用于生成子应用程序、控制它们以及响应它们输出中的预期模式。子应用程序可以是任何可执行文件(例如,在您的例子中,另一个python脚本)。它的工作方式与unix工具expect类似。

linuts answer在您的简单示例中工作得很好,但是为了将来读者的利益,我强烈建议不要使用这种方法在Python脚本之间进行通信。

这种方法是对几乎没有其他可用选项时的一种回溯。Pexpect,保佑它的心脏,也许确实是一个好程序,但它只是给一个糟糕的界面技术画上了一张笑脸。像这样的命令行控制通常依赖于时间,很快就会使它变得乏味和容易出错。只有当你别无选择时才使用它。

Python为脚本编写带来了许多更强大的方法。除非您不能访问脚本内部(使用Python,您几乎总是可以访问),否则应该编写harness.py脚本,将三方脚本作为库导入,并通过直接调用其方法/函数以编程方式控制它。

您当前的困境可能不允许这样做,但是对于Python脚本,命令行通信应该是最后的选择,而不是第一个。

尝试:

p.stdin.write('a\n')
p.stdin.write('b\n')

相关问题 更多 >