Python: 运行 子进程中的命令

Python: running a command within a subprocess

我是 python 及其子进程模块的新手,但我想弄清楚如何在子进程中获取 运行 的命令。具体来说,我在原始命令行界面模式 (http://magicseteditor.sourceforge.net/doc/cli/cli) 中 运行ning Magic Set Editor 2,我想要一个可以获取它并从中导出一堆图像的脚本。通过交互式 CLI 在 cmd.exe 中执行此操作很简单:

mse --cli setName.mse-set
//entered the interactive CLI now.
> write_image_file(file:set.cards[cardNumber].name+".png", set.cards[cardNumber]

然后将 png 文件写入我的文件夹,目前一切顺利。我可以使用原始命令行完成同样的事情:

mse --cli setName.mse-set --raw
//entered the raw CLI now.
write_image_file(file:set.cards[cardNumber].name+".png", set.cards[cardNumber]

再次实现 png 和所有这些。现在的诀窍是,如何让 python 脚本来做同样的事情?我当前的脚本如下所示:

import subprocess

s = subprocess.Popen("mse --cli setName.mse-set --raw",shell=True)
s.communicate("write_image_file(file:set.cards[1].name+'.png',set.cards[1]")

我有 shell=True 因为在 cmd.exe 中它似乎打开了一个新的 shell,但是当我 运行 这个脚本它只是打开 shell 并且似乎没有 运行 第二行,它坐在那里等待我的输入,这是我希望脚本提供的。

我找到了另一种方法,但它仍然不太适合我:

from subprocess import Popen, PIPE

s = Popen("mse --cli setName.mse-set --raw",stdin=PIPE)
s.communicate("write_image_file(file:set.cards[1].name+'.png',set.cards[1]")

...因为我收到错误:

Traceback (most recent call last):
  File "cardMaker.py", line 6, in <module>
    s.communicate("write_image_file(file:set.cards[1].name+'.png',set.cards[1]")
  File "C:\Python34\lib\subprocess.py", line 941, in communicate
    self.stdin.write(input)
TypeError: 'str' does not support the buffer interface

编辑:解决了最初的问题后,我还有一个问题;我如何向它发送多个命令?具有相同命令的另一个 s.communicate 行因错误而失败:Cannot send input after starting communication.

来自subprocess-

的文档

Popen.communicate(input=None, timeout=None)

Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate. The optional input argument should be data to be sent to the child process, or None, if no data should be sent to the child. The type of input must be bytes or, if universal_newlines was True, a string.

(强调我的)

您需要将字节字符串作为输入发送到 communicate() 方法,示例 -

from subprocess import Popen, PIPE

s = Popen("mse --cli setName.mse-set --raw",stdin=PIPE)
s.communicate(b"write_image_file(file:set.cards[1].name+'.png',set.cards[1]")

此外,您应该将命令作为列表发送到 运行,示例 -

from subprocess import Popen, PIPE

s = Popen(['mse', '--cli', 'setName.mse-set', '--raw'],stdin=PIPE)
s.communicate(b"write_image_file(file:set.cards[1].name+'.png',set.cards[1]")