communication()阻塞直到子进程返回,所以循环中的其余各行仅在子进程完成运行 后
才能执行。从stderr读取也将阻止,除非您像这样逐个字符地读取:
import subprocessimport syschild = subprocess.Popen(command, shell=True, stderr=subprocess.PIPE)while True: out = child.stderr.read(1) if out == '' and child.poll() != None: break if out != '': sys.stdout.write(out) sys.stdout.flush()
这将为您提供实时输出。取自Nadia在这里的答案。
您显然可以使用subprocess.communicate,但我认为您正在寻找实时输入和输出。
readline被阻止,因为该过程可能正在等待您的输入。您可以逐个字符地阅读以克服此问题,如下所示:
import subprocessimport sysprocess = subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)while True: out = process.stdout.read(1) if out == '' and process.poll() != None: break if out != '': sys.stdout.write(out) sys.stdout.flush()



