使子进程保持活动状态并继续向其发送命令?python

发布于 2021-01-29 19:27:19

如果我subprocess使用给定的命令在python中生成新代码(假设我使用该python命令启动python解释器),如何将新数据发送到进程(通过STDIN)?

关注者
0
被浏览
49
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    使用标准子流程模块。您使用subprocess.Popen()启动该过程,该过程将在后台运行(即与Python程序同时运行)。调用Popen()时,您可能希望将stdin,stdout和stderr参数设置为subprocess.PIPE。然后,您可以使用返回对象上的stdin,stdout和stderr字段来写入和读取数据。

    未经测试的示例代码:

    from subprocess import Popen, PIPE
    
    # Run "cat", which is a simple Linux program that prints it's input.
    process = Popen(['/bin/cat'], stdin=PIPE, stdout=PIPE)
    process.stdin.write(b'Hello\n')
    process.stdin.flush()
    print(repr(process.stdout.readline())) # Should print 'Hello\n'
    process.stdin.write(b'World\n')
    process.stdin.flush()  
    print(repr(process.stdout.readline())) # Should print 'World\n'
    
    # "cat" will exit when you close stdin.  (Not all programs do this!)
    process.stdin.close()
    print('Waiting for cat to exit')
    process.wait()
    print('cat finished with return code %d' % process.returncode)
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看