【问题标题】:Python subprocess module - unexpected behaviorPython 子进程模块 - 意外行为
【发布时间】:2011-03-09 01:16:10
【问题描述】:

我需要使用标准输入/标准输出将 C 控制台程序(作为子进程)与 Python 接口。

C 程序更是如此:

    tmp = 0.0;  
    printf("\ninput>>");
    scanf_s("%f",&tmp);
    printf ("\ninput was: %f",tmp);

    tmp = 0.0;
    printf("\ninput>>");
    scanf_s("%f",&tmp);
    printf ("\ninput was: %f",tmp);

    tmp = 0.0;
    printf("\ninput>>");
    scanf_s("%f",&tmp);
    printf ("\ninput was: %f",tmp);

使用 python 子进程模块我需要从这个程序中读取数据,写一些东西,然后再次读取等等。我使用了以下代码:

>>> p=subprocess.Popen(['C:\T.exe'],stdout=subprocess.PIPE,stdin=subprocess.PIPE)
>>> o,i=communicate('123\n')

o 的输出是:

input>>
input was: 123.000000
input>>
input was: 0.000000
input>>
input was: 0.000000

我希望子进程等待输入,直到另一个 o,i=communicate() 调用。为什么它在没有任何输入的情况下进行到程序的末尾?如何解决?

【问题讨论】:

  • 这在过去也曾咬过我一次。 :)

标签: python c subprocess


【解决方案1】:

每个进程最多可以调用一次communicate(),因为communicate() 等待子进程终止。要重复读取/写入进程的标准流,请使用Popen 类的stdoutstdin 属性。

【讨论】:

  • 如果我使用 p.stdout.read(10) 那么 python shell 没有响应,直到我手动关闭进程。然后它输出''。与 .readline 和 .readlines 相同。那可能是什么?
  • read(10) 一直等到遇到 EOF 或已读取 10 个字节。我对此没有什么经验,但是您应该使用select 或后台线程来轮询并从流中读取。 subprocess 文档中还有关于死锁的警告。
  • 你的“选择”是什么意思?
  • 顺便说一句,p.stdin.write() 完美。并且所有 p.stdout.read*() 只有在子进程终止后才能正常工作。
猜你喜欢
  • 2011-09-03
  • 1970-01-01
  • 2021-04-01
  • 1970-01-01
  • 2014-11-26
  • 2013-08-16
  • 2013-06-25
  • 2014-03-30
  • 1970-01-01
相关资源
最近更新 更多