【问题标题】:Use python to launch programm in 'terminal mode' and add commands使用python以“终端模式”启动程序并添加命令
【发布时间】:2019-03-26 16:49:14
【问题描述】:

我使用 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 解释器并执行脚本之前终止进程关于如何优雅地解决这个问题而没有延迟的任何想法?

【问题讨论】:

  • subprocess.Popen + .communicate() 是推荐的方式。
  • @meowgoesthedog 将其发布为答案,并尽可能详细说明。我刚刚学到了一些东西。
  • nuketerminal = subprocess.Popen(nuke + " -t") 后跟 nuketerminal.communicate("nuke.allNodes()") 似乎不起作用。启动 nuke 需要相当长的时间,因为它需要检查许可证。也许在解释器准备好之前,communicate() 已经发送了命令?还是我对命令做了一些废话?
  • 一个问题是 communicate 仅在子进程终止时返回,因此必须一次性提供所有输入,这可能不适合您的需要。它还需要 binary 输入数据,每行末尾都有换行符。如果您需要按程序生成输入,例如如果满足 Python 脚本中的条件,告诉nuke 退出,您可能需要通过管道传送到它的stdin

标签: python subprocess


【解决方案1】:
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()

【讨论】:

  • p.wait() 将等待进程结束并返回返回码。
猜你喜欢
  • 2018-01-11
  • 1970-01-01
  • 2021-06-04
  • 2021-08-04
  • 2018-12-12
  • 2019-10-21
  • 2019-06-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多