当Python子进程在运行时与之通信

3
我正在运行一个子进程,以“命令”模式运行软件(该软件是The Foundry的Nuke,如果您知道该软件)。
在命令模式下,此软件正在等待用户输入。此模式允许创建无需任何UI的合成脚本。
我编写了如下代码来启动进程,找到应用程序启动完成后尝试向进程发送一些命令,但stdin似乎不能正确地发送命令。
以下是我用于测试此进程的示例代码。
import subprocess

appPath = '/Applications/Nuke6.3v3/Nuke6.3v3.app/Nuke6.3v3' readyForCommand = False

commandAndArgs = [appPath, '-V', '-t'] 
commandAndArgs = ' '.join(commandAndArgs) 
process = subprocess.Popen(commandAndArgs, 
                           stdin=subprocess.PIPE, 
                           stdout=subprocess.PIPE, 
                           stderr=subprocess.STDOUT, 
                           shell=True, )

while True:
    if readyForCommand:
        print 'trying to send command to nuke...'
        process.stdin.write('import nuke')
        process.stdin.write('print nuke')
        process.stdin.write('quit()')
        print 'done sending commands'
        readyForCommand = False
    else:
        print 'Reading stdout ...'
        outLine = process.stdout.readline().rstrip()
        if outLine:
            print 'stdout:', outLine

            if outLine.endswith('getenv.tcl'):
                print 'setting ready for command'
                readyForCommand = True

    if outLine == '' and process.poll() != None:
        print 'in break!'
        break

print('return code: %d' % process.returncode) 

当我在终端中运行核弹并发送相同的命令时,这是我得到的结果:
sylvain.berger core/$ nuke -V -t
[...]
Loading /Applications/Nuke6.3v3/Nuke6.3v3.app/Contents/MacOS/plugins/getenv.tcl
>>> import nuke
>>> print nuke
<module 'nuke' from '/Applications/Nuke6.3v3/Nuke6.3v3.app/Contents/MacOS/plugins/nuke/__init__.pyc'>
>>> quit()
sylvain.berger core/$ 

有什么想法,为什么标准输入(stdin)不能正确发送命令?谢谢。

2个回答

3

你的代码将发送文本

import nukeprint nukequit()

没有换行符,因此Python实例不会尝试执行任何操作,所有内容都只是在缓冲区中等待换行符。


0

subprocess 模块不适用于与进程进行 交互式 通信。最多,您可以提供一个预先计算好的标准输入字符串,然后读取其 stdout 和 stderr:

p = Popen(..., stdin=PIPE, stdout=PIPE, stderr=PIPE)
out, err = p.communicate(predefined_stdin)

如果您需要交互,请考虑使用pexpect


子进程模块确实用于交互式通信。对于非交互式情况,您可以使用 os.system - tobyodavies
1
问题出现在当有复杂的输入输出交互,导致子进程使用的管道填满时。在简单情况下,subprocess 可以胜任(当然,你对缺少换行符的回答也是正确的)。我只是说,如果情况变得复杂,subprocess 最终可能会超出它的极限。 - torek

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接