【问题标题】:Python subprocess.Popen does not work with stdoutPython subprocess.Popen 不适用于标准输出
【发布时间】:2017-03-24 10:33:08
【问题描述】:

我需要实现一个外部应用程序来计算 Modbus 通信的 CRC 值。 可执行文件需要输入字符串并返回如下输出:

CRC16 = 0x67ED / 26605
CRC16 (Modbus) = 0x7CED / 31981

我调用程序,然后手动输入。

p = Popen(["some_file.exe", "-x"], stdin=PIPE)
p.communicate("some_string")

到目前为止一切正常。

但是,我想将输出保存到变量或其他东西(没有额外的文件)以供进一步使用。

我知道有 stdout 和 stderr 参数,但是在输入时

p = Popen([file, "-x"], stdin=PIPE, stdout=PIPE, stderr=PIPE)

什么都没有发生。

有人知道该怎么做吗?

提前致谢。

PS:在 Windows 7 上使用 Python 2.7。

【问题讨论】:

    标签: python python-2.7 subprocess popen


    【解决方案1】:

    要获取 ls 的输出,请使用 stdout=subprocess.PIPE。

    proc = subprocess.Popen('ls', stdout=subprocess.PIPE)
    output = proc.stdout.read()
    print output
    

    获取自:Pipe subprocess standard output to a variable

    注意:

    如果您使用标准输入作为 PIPE,您必须分配一个值,如下例所示:

    grep = Popen('grep ntp'.split(), stdin=PIPE, stdout=PIPE)
    ls = Popen('ls /etc'.split(), stdout=grep.stdin)
    output = grep.communicate()[0]
    

    如果值是由控制台使用 PIPE 给出的,则必须分配标准输入值读数 系统标准输入

    【讨论】:

    • 感谢您的回复。我不知道,但这似乎不起作用。我需要给程序一个输入,所以需要有一个stdin=PIPE。只使用这个参数很好,但添加 stdout=PIPE 不是。我什至没有达到可以写入变量output=...的地步
    • @mulm 如果你使用stdin=PIPE,你必须为标准输入分配一个值,否则它将为空。
    【解决方案2】:

    好的,我想通了。

    它在较早的帖子中说: How do I write to a Python subprocess' stdin?

    p.communicate() 只是等待以下形式的输入:

    p = Popen(["some_file.exe", "-x"], stdout=PIPE, stdin=PIPE, stderr=PIPE)
    output = p.communicate(input="some_string")[0]
    

    然后输出包含接收到的所有信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-30
      • 2021-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-21
      • 1970-01-01
      • 2010-10-17
      相关资源
      最近更新 更多