如何写入 Python 子进程的标准输入? [英] How do I write to a Python subprocess' stdin?

查看:95
本文介绍了如何写入 Python 子进程的标准输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个 Python 脚本来启动一个子进程,并写入到子进程的标准输入中.我还希望能够确定在子进程崩溃时要采取的操作.

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.

我尝试启动的过程是一个名为 nuke 的程序,它有自己的内置 Python 版本,我希望能够向其提交命令,然后告诉它命令执行后退出.到目前为止,我已经发现,如果我在命令提示符下启动 Python,然后将 nuke 作为子进程启动,那么我可以输入命令到 nuke,但是我我希望能够将所有这些都放在一个脚本中,以便主 Python 程序可以启动 nuke,然后写入它的 标准输入(从而进入其内置的 Python 版本)并告诉它做一些时髦的事情,所以我写了一个启动 的脚本nuke 像这样:

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"])

然后什么都没有发生,因为 nuke 正在等待用户输入.我现在如何写入标准输入?

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

我这样做是因为我正在运行一个带有 nuke 的插件,这会导致它在渲染多个帧时间歇性崩溃.所以我希望这个脚本能够启动 nuke,告诉它做一些事情,然后如果它崩溃,再试一次.因此,如果有一种方法可以在发生崩溃的情况下仍然正常运行,那就太好了.

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.

推荐答案

最好使用 沟通:

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:

使用communication() 而不是.stdin.write、.stdout.read 或.stderr.read 来避免由于任何其他操作系统管道缓冲区填满并阻塞子进程而导致的死锁.

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.

这篇关于如何写入 Python 子进程的标准输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆