python - 使用python以“终端模式”启动程序并添加命令
问题描述
我使用 subprocess 模块通过在可执行文件后添加一个标志来以“终端模式”启动程序,如下所示:
subprocess.call(nuke + " -t ")
这导致终端模式,因此所有以下命令都在程序的上下文中(我的猜测是它是程序 python 解释器)。
Nuke 11.1v6, 64 bit, built Sep 8 2018. Copyright (c) 2018 The Foundry Visionmongers Ltd. All Rights Reserved. Licence expires on: 2020/3/15
>>>
如何继续从启动终端模式的 python 脚本向解释器推送命令?你将如何从脚本中退出这个程序解释器?
编辑:
nuketerminal = subprocess.Popen(nuke + " -t " + createScript)
nuketerminal.kill()
在加载 python 解释器并执行脚本之前终止进程关于如何优雅地解决这个问题而没有延迟的任何想法?
解决方案
from subprocess import Popen, PIPE
p = subprocess.Popen([nuke, "-t"], stdin=PIPE, stdout=PIPE) # opens a subprocess
p.stdin.write('a line\n') # writes something to stdin
line = p.stdout.readline() # reads something from the subprocess stdout
当您的主进程和子进程都将等待输入时,不同步读取和写入可能会导致死锁。
您可以等待子流程结束:
return_code = p.wait() # waits for the process to end and returns the return code
# or
stdoutdata, stderrdata = p.communicate("input") # sends input and waits for the subprocess to end, returning a tuple (stdoutdata, stderrdata).
或者您可以使用以下命令结束子流程:
p.kill()