如何打开命令提示符以及使用python脚本运行的命令?

问题描述 投票:1回答:2

我尝试了以下方法来打开命令提示符并运行示例命令。但它立即关闭:

import os
# as of now i am just passing cd /../, later will be changing to a different command
os.system("start /wait cmd /c {cd /../}")

我也试过这种方式,但这会打开两个命令shell:

import os
os.system("start /B start cmd.exe @cmd /k cd /d D:")

Two commands shell are being opened

是否可以只打开一个命令提示符并运行命令?

python windows
2个回答
3
投票
import subprocess

cmd = subprocess.Popen('cmd.exe /K cd /') 

#subprocess.Popen('cmd.exe /K netstat') # run cmd commands like netstat,..etc
#subprocess.Popen('cmd.exe /K python') # open cmd in  Python live interpreter mode
#subprocess.Popen('cmd.exe /K my_script.py') # run your python script

阅读更多https://docs.python.org/3/library/subprocess.html#subprocess.Popen


2
投票

CMD窗口将运行您提供的命令,然后在完成时立即关闭,如果要保持窗口打开,则需要发送暂停命令:

os.system(“你的命令”)

os.system(“暂停”)

© www.soinside.com 2019 - 2024. All rights reserved.