如果我subprocess使用给定的命令在python中生成新代码(假设我使用该python命令启动python解释器),如何将新数据发送到进程(通过STDIN)?
subprocess
python
使用标准子流程模块。您使用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)