subprocess.Popen错过了最后输出的字符

时间:2017-08-04 13:24:01

标签: python python-2.7 subprocess

我有一个用C ++编写的可执行文件,它将一些json写入标准输出。

例如,在终端中运行它,我有,

PS C:\Users\laerne\Projects\pylol> C:\Users\laerne\Projects\d\master\build\bin\Debug\software.exe --opt-descr
[
    {
        "name": "",
        "options": [
        ]
    },
    {
        "name": "run"
    },
    {
        "name": "normal-from-mesh"
    },
    {
        "name": "info"
    },
    {
        "name": "world-space-direction"
    },
    {
        "name": "position-from-mesh"
    },
    {
        "name": "ambient-occlusion"
    },
    {
        "name": "bent-normal-from-mesh"
    },
    {
        "name": "ambient-occlusion-from-mesh"
    },
    {
        "name": "curvature-from-mesh"
    },
    {
        "name": "position"
    },
    {
        "name": "normal-world-space"
    },
    {
        "name": "texture-from-mesh"
    },
    {
        "name": "height-from-mesh"
    },
    {
        "name": "thickness-from-mesh"
    },
    {
        "name": "curvature"
    },
    {
        "name": "color-from-mesh"
    },
    {
        "name": "opacity-mask-from-mesh"
    },
    {
        "name": "uv-map"
    }
]

我现在想从python中读取json。为此,我调用subprocess来生成json。

subprocess.Popen(
  [r"C:\Users\laerne\Projects\d\master\build\bin\Debug\software.exe","--opt-descr"],
  stdout=subprocess.PIPE ).stdout.read()

然而,这会返回空字符串!尝试使用更大的json文本,我注意到最后几个~200~400个字符总是被删除,我不知道为什么。你能帮我猜一下为什么python顽固地拒绝阅读最后几个字符吗?

非常感谢你!

1 个答案:

答案 0 :(得分:0)

您忘了等待子流程完成。尝试:

p = subprocess.Popen(  [r"C:\Users\laerne\Projects\d\master\build\bin\Debug\software.exe","--opt-descr"],
  stdout=subprocess.PIPE)
p.wait()
print(p.stdout.read())

或者您可以尝试使用check_output:

print(subprocess.check_output([r"C:\Users\laerne\Projects\d\master\build\bin\Debug\software.exe","--opt-descr"])

编辑:还有第二方 - 一个输出数据的应用程序。记得在C ++应用程序中刷新stdout。