繁体   English   中英

使用 python 运行 cmd 文件

[英]Run cmd file using python

我有一个包含 100 行命令的 cmd 文件“file.cmd”。

例子

 pandoc --extract-media -f docx -t gfm "sample1.docx" -o "sample1.md"
 pandoc --extract-media -f docx -t gfm "sample2.docx" -o "sample2.md"
 pandoc --extract-media -f docx -t gfm "sample3.docx" -o "sample3.md"

我正在尝试使用脚本运行这些命令,这样我就不必将 go 转到文件并单击它。 这是我的代码,它导致没有 output:

file1 = open('example.cmd', 'r') 
Lines = file1.readlines()
# print(Lines)
for i in Lines:
    print(i)
    os.system(i)

您无需逐行阅读 cmd 文件。 您可以简单地尝试以下操作:

import os
os.system('myfile.cmd')

或使用子流程模块:

import subprocess
p = subprocess.Popen(['myfile.cmd'], shell = True, close_fds = True)
stdout, stderr = proc.communicate()

例子:

myfile.cmd

@ECHO OFF
ECHO Grettings From Python!
PAUSE

脚本.py

import os
os.system('myfile.cmd')

cmd 将打开:

Greetings From Python!
Press any key to continue ...

您可以通过以下方式了解返回退出代码来调试问题:

import os
return_code=os.system('myfile.cmd')
assert return_code == 0 #asserts that the return code is 0 indicating success!

注意: os.system 通过在 C 中调用system()来工作,在命令后最多只能占用 65533 arguments(因此这是一个 16 位问题)。 再提供一个参数将导致返回代码32512 (which implies the exit code 127).

subprocess模块提供了更强大的工具来生成新进程并检索它们的结果; 使用该模块优于使用此 function ( os.system('command') )。

因为它是一个命令文件( cmd ),并且只有 shell 可以运行它,所以 shell 参数必须设置为 true。 由于您将 shell 参数设置为 true,因此命令必须是字符串形式而不是列表。

使用Popen方法生成一个新进程,并使用 communicte 等待该进程(您也可以将其超时)。 如果您希望与子进程通信,请提供PIPES (参见 mu 示例,但您不必这样做!)

以下代码适用于 python 3.3 及更高版本

import subprocess

try:
    proc=subprocess.Popen('myfile.cmd', shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
    outs, errs = proc.communicate(timeout=15)  #timing out the execution, just if you want, you dont have to!
except TimeoutExpired:
    proc.kill()
    outs, errs = proc.communicate()

对于较旧的 python 版本

proc = subprocess.Popen('myfile.cmd', shell=True)
t=10
while proc.poll() is None and t >= 0:
    print('Still waiting')
    time.sleep(1)
    t -= 1

proc.kill()

在这两种情况下(python 版本),如果您不需要timeout功能并且不需要与子进程交互,那么只需使用:

proc = subprocess.Popen('myfile.cmd', shell=True)
proc.communicate()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM