python - 如何从 python 脚本打开 .cmd 文件

标签 python python-3.x

我有一个 .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/

相关文章:

Python - 我需要了解旧式类吗?

python - 使用加权距离度量的 Scikit-learn 最近邻搜索

python - ValueError:太多值无法在OpenCV项目中解压缩

python - 根据满足条件求两点之间的厚度

Python - mysql - 记录生成警告的查询

Python-Gmail邮件检索/下载

python - 如何在提取包含多个值的 CSV 文件后构建实例

python-3.x - 使用 pandas 转换文件中的数据时出现 KeyError5

python - 优先考虑 celery 队列/任务

python - 值在 for 循环内自动更新