[英]Python: running a command within a subprocess
我對python及其子進程模塊非常陌生,但是我試圖弄清楚如何讓命令在子進程中運行。 具體來說,我正在原始命令行界面模式( http://magicseteditor.sourceforge.net/doc/cli/cli )上運行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(輸入=無,超時=無)
與進程交互:將數據發送到stdin。 從stdout和stderr讀取數據,直到到達文件末尾。 等待進程終止。 可選的輸入參數應該是要發送到子進程的數據,如果沒有數據應該發送到子進程,則為None。 輸入類型必須為字節,或者,如果universal_newlines為True,則為字符串。
(強調我的)
您需要發送一個字節字符串作為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]")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.