首页 文章

Python subprocess.Popen不适用于stdout

提问于
浏览
1

我需要实现一个外部应用程序来计算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 .

2 回答

  • 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

    注意:

    如果使用stdin作为PIPE,则必须分配一个值,如下例所示:

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

    如果控制台使用PIPE给出值,则必须分配读取sys.stdin的stdin值

  • 0

    好的,我明白了 .

    它在一篇较老的帖子中说: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]
    

    然后输出具有收到的所有信息 .

相关问题