简体   繁体   English

是否可以将 subprocess.Popen 的 stdout 重新连接到 sys.stdout? (蟒蛇3)

[英]is it possible to reconnect subprocess.Popen's stdout to sys.stdout? (python3)

I have a python program that runs another program using popen.我有一个 python 程序,它使用 popen 运行另一个程序。 Is it possible to read from the programme's output for a while, and the connect the subprogram's output to sys.stdout , and allow it to run in parallel as if I had started it without the stdout=subprocess.PIPE option?是否可以从程序的输出中读取一段时间,并将子程序的输出连接到sys.stdout ,并允许它并行运行,就像我在没有stdout=subprocess.PIPE选项的情况下启动它一样?

wrapper:包装器:

#! /usr/bin/env python3

import subprocess
from time import sleep
import sys

p = subprocess.Popen(
  ["./count.py"],
  stdout=subprocess.PIPE,
)

for line in iter(p.stdout.readline,''):
  l = line.decode('utf-8')
  sys.stdout.write(">>" + l)
  if "8" in l:
    # somehow reconnect p.stdout to sys.stdout
    break

sleep(1)

print("now do some stuff in parallel")

sleep(1)

p.terminate()

test program:测试程序:

#! /usr/bin/env python

from time import sleep
import sys

for x in range(1,100):
  sleep(.1)
  print x
  sys.stdout.flush()

output:输出:

$ ./wrapper.py
>>1
>>2
>>3
>>4
>>5
>>6
>>7
>>8
now do some stuff in parallel

is it possible to do this?是否有可能做到这一点?

$ ./wrapper.py
>>1
>>2
...
>>7
>>8
9
10
...
18
19
now do some stuff in parallel
20
21
...
28
29

You cannot "reconnect" the file descriptors of a subprocess you've already launched (except perhaps with very dirty and OS-specific tricks).您不能“重新连接”已经启动的子进程的文件描述符(除非使用非常脏和特定于操作系统的技巧)。 The only file descriptor you have control over, is the one that's still in your process, and it's only useful for reading.您可以控制的唯一文件描述符是仍在您的进程中的文件描述符,它仅用于读取。 So if you want things to go to stdout, then everything that comes into the read end would have to be copied to stdout somehow.因此,如果您希望将内容转到标准输出,那么进入读取端的所有内容都必须以某种方式复制到标准输出。

Fortunately, you can always spawn another subprocess to do that.幸运的是,你总是可以产生另一个子进程来做到这一点。 This is just the kind of thing that the handy Unix utility cat does well.这正是方便的 Unix 实用工具cat擅长的事情。

subprocess.Popen(
  ["/bin/cat"],
  stdin=p.stdout,
)

This will basically create a pipeline, where you pipe the output of one process into another process.这将基本上创建一个管道,您可以在其中将一个进程的输出通过管道传输到另一个进程中。 It can be very useful.它可能非常有用。 In this case the other process ( cat ) just outputs to stdout.在这种情况下,另一个进程 ( cat ) 只是输出到 stdout。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM