首页 > 解决方案 > 带有标准输入的 Python 子进程

问题描述

我正在尝试使用 python 子进程来调用第三方命令ParseAddress。该命令ParseAddress打印出一行文本,要求用户输入地址列表,然后根据输入打印出堆栈跟踪信息。如果我手动运行命令,它看起来像:

$ParseAddress Appname                       <- Run the command in console
Paste the addresses - new line to continue
[0]0xaaaaaaaa                               <- a User paste a list of address here
[1]0xbbbbbbbb
[2]0xcccccccc
                                            <- the user type 'enter' to continue
Stack Trace info:                           <-- results of running the ParseAddress
0xaaaaaaaa: Test::info::Runtest
0xbbbbbbbb: Test::info::SingleTestCase
0xcccccccc: ...

所以,如果我已经有一个文本格式的地址列表,我认为 subprocess() 和communicate() 在这种情况下会很有帮助:

cmd = subprocess.Popen([ParseAddress, Appname], stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT)
output, error = cmd.communicate(input="[0]0xaaaaaaaa\n[1]0xbbbbbbbb\n[2]0xcccccccc\n\n")
print(output)

当我将子进程与communite()一起使用时,控制台输出为:

$ParseAddress Appname
Paste the addresses - new line to continue
0xaaaaaaaa: ?? ??:0                         <- subprocess.PIPE?
0xbbbbbbbb: ?? ??:0
0xcccccccc: ?? ??:0

Stack Trace info: <-- no results from the ParseAddress since the address info are in incorrect format

如果我使用

cmd.communicate(input="[0]0xaaaaaaaa\r\n[1]0xbbbbbbbb\r\n[2]0xcccccccc\r\n\r\n")

结果是:

$ParseAddress Appname
Paste the addresses - new line to continue
                                           <-- No address here, no ideas why
Stack Trace info:

我的问题是为什么参数从更改[0]0xaaaaaaaa0xaaaaaaaa: ?? ??:0

使用通信()的正确方法是什么?

环境:
Ubuntu 18.04
Python 2.7.16 :: Anaconda, Inc.

标签: pythonsubprocesscommunicate

解决方案


推荐阅读