![](/img/trans.png)
[英]How to push in a command in terminal from a python3 batch file after having opened a new cmd window?
[英]How to control a command window opened from a .cmd file using Python
有一個名為startup.cmd的文件,該文件設置一些環境變量,運行一些准備命令,然后執行:
start "startup" cmd /k
這將打開一個名為啟動的命令外殼。 我嘗試自動化的手動過程是在此shell中輸入以下命令: get startup.xml
。 我認為在Python中執行此操作的正確方法如下所示:
import subprocess
p = subprocess.Popen('startup.cmd', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
getcommand = 'get startup.xml'
servercommand = 'startserver'
p.stdin.write(getcommand)
p.stdin.write(startserver)
(stdoutdata, stderrdata) = p.communicate()
print stdoutdata
print stderrdata
但是這些命令似乎不在外殼中執行。 我想念什么? 此外,無論將Shell設置為True還是False,都會出現命令Shell。
我在子流程的文檔中找到了此警告,
警告使用communication()而不是.stdin.write,.stdout.read或.stderr.read,以避免由於任何其他OS管道緩沖區填充和阻塞子進程而導致死鎖。
所以我的建議是使用通訊來發送命令。
import subprocess
p = subprocess.Popen('startup.cmd', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
command = 'get startup.xml\n'
command += 'startserver\n'
(stdoutdata, stderrdata) = p.communicate(command)
print stdoutdata
print stderrdata
這是一個新過程,因此無法直接與Popen通信。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.