简体   繁体   English

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

[英]How can I communicate between two python scripts?

I have a 3d party python script which takes input from the command line.我有一个 3d 方 python 脚本,它从命令行获取输入。 The relevant code from this script (input.py) looks like the following:此脚本 (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...

I'm trying to write another python script (harness.py) to generate the inputs for the above script.我正在尝试编写另一个 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()

From the command line, I run:从命令行,我运行:

$ 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

If I only have one input in the first script, then I can make the second script work by removing the second write call.如果我在第一个脚本中只有一个输入,那么我可以通过删除第二个 write 调用来使第二个脚本工作。 If the first script requires more than one input, then I get the above error.如果第一个脚本需要多个输入,则会出现上述错误。

Try:尝试:

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

linuts answer works well in your simple example, but for the benefit of future readers, I would strongly recommend against using this methodology for communicating between Python scripts. linuts answer 在您的简单示例中效果很好,但为了未来读者的利益,我强烈建议不要使用这种方法在 Python 脚本之间进行通信。

This method is a throwback to when few other options were available.这种方法是对几乎没有其他可用选项的回归。 Pexpect, bless its heart, may indeed be a good program, but it merely puts a happy face on a miserable interface technique. Pexpect,保佑它的心,可能确实是一个好程序,但它只是在一个悲惨的界面技术上装了一张幸福的脸。 Command-line control such as this is often timing dependent, quickly making it tedious and error-prone.诸如此类的命令行控制通常依赖于时间,很快就变得乏味且容易出错。 Use it only when you have no other choice.只有在别无选择时才使用它。

Python brings many much more powerful methods to scripting. Python 为脚本编写带来了许多更强大的方法。 Unless you don't have access to script internals (with Python, you almost always do) you should instead write your harness.py script to import the 3-party script as a library and control it programmatically by calling its methods/functions directly.除非您无法访问脚本内部(使用 Python,您几乎总是这样做),否则您应该编写harness.py 脚本来将 3 方脚本作为库导入并通过直接调用其方法/函数以编程方式控制它。

Your current predicament may not allow it, but with Python scripts, command-line communication should be the last choice, not the first.您目前的困境可能不允许这样做,但是对于 Python 脚本,命令行通信应该是最后的选择,而不是第一个。

You should check out Pexpect .你应该看看Pexpect

Pexpect is a pure Python module for spawning child applications; Pexpect 是一个纯 Python 模块,用于生成子应用程序; controlling them;控制它们; and responding to expected patterns in their output.并响应其 output 中的预期模式。 The child application can be any executable (for instance, as in your case, another python script).子应用程序可以是任何可执行文件(例如,在您的情况下,另一个 python 脚本)。 It works similarly to the unix tool "expect".它的工作原理类似于 unix 工具“expect”。

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

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