如何使用 Python 控制从 .cmd 文件打开的命令窗口
有一个名为startup.cmd的文件,它设置一些环境变量,运行一些准备命令,然后执行以下操作:
start "startup" cmd /k
这将打开一个名为startup的命令shell。我尝试自动化的手动过程是在该 shell 中输入以下命令:getstartup.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 中执行。我缺少什么?此外,无论 shell 设置为 True 还是 False,命令 shell 都会出现。
There's a file named startup.cmd that sets some environment variables, runs some preparation commands, then does:
start "startup" cmd /k
Which opens a command shell named startup. The manual process I'm trying to automate is to then enter the following command into this shell: get startup.xml
. I thought the correct way to do this in Python would be something like this:
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
But those commands don't seem to be executing in the shell. What am I missing? Also, the command shell appears regardless of whether shell is set to True or False.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我在子进程的文档中发现了这个警告,
所以我的建议是使用通信来发送命令。
I found this warning in subprocess's document,
So my suggestion is to use communicate to send your command.
这是一个新进程,因此无法直接与 Popen 通信。
This is a new process, so one cannot communicate directly with Popen.