我想读一个子进程'stdout的第一个字节,知道它已经开始运行了.之后,我想丢弃所有进一步的输出,这样我就不用担心缓冲区了.
做这个的最好方式是什么?
澄清:我希望子进程继续与我的程序一起运行,我不想等待它终止或类似的东西.理想情况下,有一些简单的方法可以做到这一点,而不是诉诸threading
,fork
或multiprocessing
.
如果我忽略输出流,或者.close()
它,如果发送的数据多于它可以容纳在其缓冲区中的数据,则会导致错误.
Dav*_*ter 68
如果你正在使用Python 3.3+,您可以使用DEVNULL
特殊的价值stdout
和stderr
丢弃子输出.
from subprocess import Popen, DEVNULL
process = Popen(["mycmd", "myarg"], stdout=DEVNULL, stderr=DEVNULL)
Run Code Online (Sandbox Code Playgroud)
或者,如果您使用的是Python 2.4+,则可以使用以下方法模拟:
import os
from subprocess import Popen
DEVNULL = open(os.devnull, 'wb')
process = Popen(["mycmd", "myarg"], stdout=DEVNULL, stderr=DEVNULL)
Run Code Online (Sandbox Code Playgroud)
但是,这并没有让您有机会读取stdout的第一个字节.
小智 2
这似乎可行,但感觉不惯用。
#!/usr/bin/env python3.1
import threading
import subprocess
def discard_stream_while_running(stream, process):
while process.poll() is None:
stream.read(1024)
def discard_subprocess_pipes(process, out=True, err=True, in_=True):
if out and process.stdout is not None and not process.stdout.closed:
t = threading.Thread(target=discard_stream_while_running, args=(process.stdout, process))
t.start()
if err and process.stderr is not None and not process.stderr.closed:
u = threading.Thread(target=discard_stream_while_running, args=(process.stderr, process))
u.start()
if in_ and process.stdin is not None and not process.stdin.closed:
process.stdin.close()
Run Code Online (Sandbox Code Playgroud)
if __name__ == "__main__":
import tempfile
import textwrap
import time
with tempfile.NamedTemporaryFile("w+t", prefix="example-", suffix=".py") as f:
f.write(textwrap.dedent("""
import sys
import time
sys.stderr.write("{} byte(s) read through stdin.\\n"
.format(len(sys.stdin.read())))
# Push a couple of MB/s to stdout, messages to stderr.
while True:
sys.stdout.write("Hello Parent\\n" * 1000000)
sys.stderr.write("Subprocess Writing Data\\n")
time.sleep(0.5)
"""))
f.flush()
p = subprocess.Popen(["python3.1", f.name],
stdout=subprocess.PIPE,
stdin=subprocess.PIPE)
p.stdin.write("Hello Child\n".encode())
discard_subprocess_pipes(p) # <-- Here
for s in range(16, 0, -1):
print("Main Process Running For", s, "More Seconds")
time.sleep(1)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
12224 次 |
最近记录: |