我有一个 .cmd
文件,我想从 python 脚本打开它。当我打开 .cmd 文件(转换器)时,它会完成其工作,而无需在命令窗口中进行任何进一步的交互。这意味着我只需从我的脚本中打开它,仅此而已。
我尝试了以下...
from subprocess import check_output
def convert():
subprocess.Popen(['[path to the .cmd file]')
...但它只打开cmd窗口几分之一秒,并且我想要运行的实际.cmd
文件没有执行。我需要更改什么才能打开路径后面的 .cmd
文件?
更新
from subprocess import Popen, PIPE
def convert():
process = Popen("cmd.exe", shell=False, universal_newlines=True, stdin=PIPE, stdout=PIPE, stderr=PIPE)
commands = r"C:\\CONVERTER\MFD2MAT\\convert.cmd\n"
out, err = process.communicate(commands)
最佳答案
我会尝试重新解释:
第一种方法:
from subprocess import Popen, PIPE
process = Popen("cmd.exe", shell=False, universal_newlines=True, stdin=PIPE, stdout=PIPE, stderr=PIPE)
commands = "C:\\Users\\praktikant3\\TESTING.cmd\n" #you can use " " for 1 line of commands or ''' ''' for several lines
out, err = process.communicate(commands)
print(out)
在制定您的命令时,请记住您的命令 以Python字符串的形式,因此:
- 确保在路径中转义前斜杠/反斜杠:C:\.. => C:\\..
- 将
\n
添加到字符串末尾以表示执行命令的换行符。
在我的代码中,只有使用 print(out)
才能看到输出,但 cmd 文件无论如何都会运行。
第二种方法:
import sys
import os
def run_command(command):
print("Running command: {}".format(command))
os.system(command)
commands = "C:\\Users\\praktikant3\\TESTING.cmd"
run_command(commands)
如果您只使用一行命令,并且不需要换行符 \n
,那么这很简洁,os.system
会为您完成此操作。此外,os.system
将在您的 IDE 中显示输出,而无需打印任何内容。
关于python - 如何从 python 脚本打开 .cmd 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50699990/