使用Python代码运行一个.bat文件

70

我尝试使用Python脚本在Windows中运行一个.bat文件。

ask.bat 文件内容如下:

Application.exe work.xml

我写 Python 代码:

import os
os.system("D:\xxx1\xxx2XMLnew\otr.bat ")

输出结果: 尝试运行文件时,命令提示符只会闪烁一下,工作不会执行。

注意:我也尝试使用反斜杠,但它也不起作用。

我还想将文件的输出保存到另一个文件中。

有人能建议我如何使脚本可运行吗?


1
你是否尝试过转义反斜杠?请尝试使用以下代码:os.system("D:\\xxx1\\xxx2XMLnew\\otr.bat ") - inspectorG4dget
将以下与编程有关的内容从英语翻译成中文。只返回已翻译的文本:如果您不想转义,请使用/而不是\ - EgMusic
1
只需要在引号前面加上r:r"D:\xxx1\xxx2XMLnew\otr.bat "
尝试:
import os
os.system(r"D:\xxx1\xxx2XMLnew\otr.bat ")
- Md Fantacher Islam
10个回答

53

这个问题在StackOverflow上已经有详细的答案了。请查看此帖子,它应该能回答你的所有问题:执行子进程失败

我已经尝试过这段代码:

batchtest.py

from subprocess import Popen
p = Popen("batch.bat", cwd=r"C:\Path\to\batchfolder")
stdout, stderr = p.communicate()

batch.bat

echo Hello World!
pause
我已经从上述线程中获取了batchtest.py示例。

嗨,das_weezul,感谢提供的信息。我尝试了那里提到的方法,但对我来说仍然存在同样的问题,在执行时,应用程序会闪烁一下然后就消失了,没有任何操作执行。 - Silver
4
@Silver:Popen() 找不到 test.bat 文件。在 文档 中指出,“如果 cwd 不是 None,子进程的当前目录会在执行前被更改为 cwd。请注意,当搜索可执行文件时,该目录不会被考虑,因此你不能相对于 cwd 指定程序路径。” - martineau
1
@martineau 他使用的路径是"C:\XMLnew",这是绝对路径,所以这不应该是问题所在。 - das_weezul
1
@das_weezul:是的,但是"test.bat"是相对路径。 - martineau
你能否直接从subprocess.Popen调用批处理文件的内容,这似乎是一个不必要的步骤。 - Jakob Bowyer
显示剩余4条评论

34
import subprocess

filepath="D:/path/to/batch/myBatch.bat"
p = subprocess.Popen(filepath, shell=True, stdout = subprocess.PIPE)

stdout, stderr = p.communicate()
print p.returncode # is 0 if success

3
shell=True 允许您运行 .bat 文件而不是 .exe 文件。 - Bob Stein
1
@BobStein-VisiBone 不是这样的。您可以从Popen调用.bat文件,而无需传递shell=True,但正如martineau在上面的答案中指出的那样,您必须指定.bat文件的绝对路径。 - Nathan

16

将路径中的 \ 替换为 /

import os
os.system("D:/xxx1/xxx2XMLnew/otr.bat ")

2
我建议使用os.path.normpath filepath="D:/xxx1/xxx2XML/otr.bat" p = Popen(filepath, shell=True, stdout = subprocess.PIPE)stdout, stderr = p.communicate() print process.returncode # 如果成功,则为0 - user1176501

6
可能最简单的方法是 ->
import os
os.chdir("X:\Enter location of .bat file")
os.startfile("ask.bat")

不确定其他操作系统,但在Windows上可以运行 :) - outcast_dreamer

5
  1. It is better to write .bat file in such way that its running is not dependent on current working directory, i.e. I recommend to put this line at the beginning of .bat file:

    cd "%~dp0"
    
  2. Enclose filepath of .bat file in double quotes, i.e.:

    os.system('"D:\\x\\so here can be spaces\\otr.bat" ["<arg0>" ["<arg1>" ...]]')
    
  3. To save output of some batch command in another file you can use usual redirection syntax, for example:

    os.system('"...bat" > outputfilename.txt')
    

    Or directly in your .bat file:

    Application.exe work.xml > outputfilename.txt
    

4

您只是忘了将其设置为原始字符串。问题出在 \ 字符上。在路径前添加 r 将解决此问题 :)

import os
os.system(r"D:\xxx1\xxx2XMLnew\otr.bat")

2

以下是我在Windows 10和Python 3.7.1(已测试)上实现的方法:

import subprocess
Quellpfad = r"C:\Users\MeMySelfAndI\Desktop"
Quelldatei = r"\a.bat"
Quelle = Quellpfad + Quelldatei
print(Quelle)
subprocess.call(Quelle)

1

python_test.py

import subprocess
a = subprocess.check_output("batch_1.bat")
print a

这将把批处理文件的输出打印到Python IDLE/运行控制台上。因此,在批处理文件中,您可以在每个步骤中回显结果以调试问题。当批处理调用出现错误时,这也在自动化中非常有用,以便轻松理解和定位错误。(在批处理文件开头放置"echo off"以避免打印所有内容)

batch_1.bat

echo off    
echo "Hello World" 
md newdir 
echo "made new directory"

0
如果您正在尝试在bat文件中调用另一个exe文件, 您必须在所调用的bat文件中使用SET Path。 set Path 应该指向exe文件所在的目录:
set PATH=C:\;C:\DOS     {Sets C:\;C:\DOS as the current search path.} 

0
如果你的.bat文件在同一个目录中:
import os
os.startfile("filename.bat")

你也可以以这种方式并行运行多个.bat文件。
os.startfile("filename.bat")
os.startfile("filename2.bat")

- 如果你想在运行.bat文件之前改变目录,请运行以下命令:
os.chdir("X:\directory_inwhich_the_code_will_run")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接