Popen.communicate()说明文件:
请注意,如果要将数据发送到进程的stdin,则需要使用
stdin = PIPE创建Popen对象。同样,要在结果元组中获得除None以外的任何内容,你还需要提供
stdout = PIPE和/或
stderr = PIPE。
替换
os.popen *
pipe = os.popen(cmd, 'w', bufsize) # ==> pipe = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE).stdin
警告使用
communication()而不是
stdin.write(),
stdout.read()或
stderr.read()来避免死锁,因为任何其他OS管道缓冲区填满并阻塞了子进程。
因此,你的示例可以编写如下:
from subprocess import Popen, PIPE, STDOUTp = Popen(['grep', 'f'], stdout=PIPE, stdin=PIPE, stderr=STDOUT) grep_stdout = p.communicate(input=b'onentwonthreenfournfivensixn')[0]print(grep_stdout.depre())# -> four# -> five# ->
在当前的Python 3版本中,你可以使用
subprocess.run,将输入作为字符串传递给外部命令并获取其退出状态,并在一次调用中将输出作为字符串返回:
#!/usr/bin/env python3from subprocess import run, PIPEp = run(['grep', 'f'], stdout=PIPE, input='onentwonthreenfournfivensixn', encoding='ascii')print(p.returnpre)# -> 0print(p.stdout)# -> four# -> five# ->



