为了账号安全,请及时绑定邮箱和手机立即绑定

使用python运行cmd文件

使用python运行cmd文件

潇潇雨雨 2023-03-08 09:54:56
我有一个包含 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"我正在尝试使用脚本运行这些命令,这样我就不必转到文件并单击它。这是我的代码,它没有输出:file1 = open('example.cmd', 'r') Lines = file1.readlines()# print(Lines)for i in Lines:    print(i)    os.system(i)
查看完整描述

2 回答

?
素胚勾勒不出你

TA贡献1827条经验 获得超9个赞

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


import os

os.system('myfile.cmd')

或使用子流程模块:


import subprocess

p = subprocess.Popen(['myfile.cmd'], shell = True, close_fds = True)

stdout, stderr = proc.communicate()

例子:


我的文件.cmd:


@ECHO OFF

ECHO Grettings From Python!

PAUSE

script.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 个参数(因此这是一个 16 位问题)。再提供一个参数将导致返回代码32512 (which implies the exit code 127).


查看完整回答
反对 回复 2023-03-08
?
有只小跳蛙

TA贡献1824条经验 获得超8个赞

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


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


使用Popen生成新进程的方法和等待该进程的通信(您也可以将其超时)。如果您希望与子进程通信,请提供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()


查看完整回答
反对 回复 2023-03-08
  • 2 回答
  • 0 关注
  • 65 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信