代码之家  ›  专栏  ›  技术社区  ›  Senthil Kumaran

子进程无法捕获标准输出-程序可能在做什么?

  •  1
  • Senthil Kumaran  · 技术社区  · 16 年前

    我有一个程序,在控制台上执行时如下:

    prog  1> output 2> error
    

    具有有效的输出和错误。但是,当我使用子流程模块执行相同的程序时。

    p = subprocess.Popen(['prog'],stdout=PIPE, stderr=PIPE,close_fds=True)
    out, err = p.communicate()
    

    out是空的,但err是正确的。这里会发生什么? 我可以做一个操作系统。系统和直接输出和错误也。但直到最近,我还一直依赖于子流程。

    有什么问题吗?这只在Linux上进行了尝试。不是在窗户上。 `

    2 回复  |  直到 16 年前
        1
  •  1
  •   gimel    16 年前

    你在Windows上试用这个吗?

    使用 close_fds 是 根据研究人员的说法,这取决于平台 subprocess.Popen() doc .

    如果 关闭 如果为true,则在执行子进程之前,除0、1和2之外的所有文件描述符都将关闭。(仅限Unix)。或者,在Windows上,如果close_fds为true,则子进程不会继承任何句柄。 请注意,在Windows上,不能将close_fds设置为true,也不能通过设置stdin、stdout或stderr重定向标准句柄 .

        2
  •  0
  •   marbdq    16 年前

    刚刚试过你的代码,对我有用:

    >>> p = subprocess.Popen(['ls'], stdout=subprocess.PIPE, stderr=subprocess.PIPE,
     close_fds=True)
    >>> out, err = p.communicate()
    >>> out
    'build\nCode\n...'
    >>> err
    ''
    

    a) 确保程序被正确调用。

    b) 导入管道正确吗?