How do I write to a Python subprocess' stdin?

╄→尐↘猪︶ㄣ 提交于 2019-11-26 03:22:28

问题


I\'m trying to write a Python script that starts a subprocess, and writes to the subprocess stdin. I\'d also like to be able to determine an action to be taken if the subprocess crashes.

The process I\'m trying to start is a program called nuke which has its own built-in version of Python which I\'d like to be able to submit commands to, and then tell it to quit after the commands execute. So far I\'ve worked out that if I start Python on the command prompt like and then start nuke as a subprocess then I can type in commands to nuke, but I\'d like to be able to put this all in a script so that the master Python program can start nuke and then write to its standard input (and thus into its built-in version of Python) and tell it to do snazzy things, so I wrote a script that starts nuke like this:

subprocess.call([\"C:/Program Files/Nuke6.3v5/Nuke6.3\", \"-t\", \"E:/NukeTest/test.nk\"])

Then nothing happens because nuke is waiting for user input. How would I now write to standard input?

I\'m doing this because I\'m running a plugin with nuke that causes it to crash intermittently when rendering multiple frames. So I\'d like this script to be able to start nuke, tell it to do something and then if it crashes, try again. So if there is a way to catch a crash and still be OK then that\'d be great.


回答1:


It might be better to use communicate:

from subprocess import Popen, PIPE, STDOUT
p = Popen(['myapp'], stdout=PIPE, stdin=PIPE, stderr=PIPE)
stdout_data = p.communicate(input='data_to_write')[0]

"Better", because of this warning:

Use communicate() rather than .stdin.write, .stdout.read or .stderr.read to avoid deadlocks due to any of the other OS pipe buffers filling up and blocking the child process.




回答2:


You can provide a file-like object to the stdin argument of subprocess.call().

The documentation for the Popen object applies here.

To capture the output, you should instead use subprocess.check_output(), which takes similar arguments. From the documentation:

>>> subprocess.check_output(
...     "ls non_existent_file; exit 0",
...     stderr=subprocess.STDOUT,
...     shell=True)
'ls: non_existent_file: No such file or directory\n'


来源:https://stackoverflow.com/questions/8475290/how-do-i-write-to-a-python-subprocess-stdin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!