我尝试使用Python脚本在Windows中运行一个.bat
文件。
ask.bat
文件内容如下:
Application.exe work.xml
我写 Python 代码:
import os
os.system("D:\xxx1\xxx2XMLnew\otr.bat ")
输出结果: 尝试运行文件时,命令提示符只会闪烁一下,工作不会执行。
注意:我也尝试使用反斜杠,但它也不起作用。
我还想将文件的输出保存到另一个文件中。
有人能建议我如何使脚本可运行吗?
我尝试使用Python脚本在Windows中运行一个.bat
文件。
ask.bat
文件内容如下:
Application.exe work.xml
我写 Python 代码:
import os
os.system("D:\xxx1\xxx2XMLnew\otr.bat ")
输出结果: 尝试运行文件时,命令提示符只会闪烁一下,工作不会执行。
注意:我也尝试使用反斜杠,但它也不起作用。
我还想将文件的输出保存到另一个文件中。
有人能建议我如何使脚本可运行吗?
这个问题在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示例。Popen()
找不到 test.bat
文件。在 文档 中指出,“如果 cwd 不是 None
,子进程的当前目录会在执行前被更改为 cwd。请注意,当搜索可执行文件时,该目录不会被考虑,因此你不能相对于 cwd 指定程序路径。” - martineau"test.bat"
是相对路径。 - martineauimport 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
shell=True
允许您运行 .bat 文件而不是 .exe 文件。 - Bob Stein将路径中的 \ 替换为 /
import os
os.system("D:/xxx1/xxx2XMLnew/otr.bat ")
import os
os.chdir("X:\Enter location of .bat file")
os.startfile("ask.bat")
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"
Enclose filepath of .bat
file in double quotes, i.e.:
os.system('"D:\\x\\so here can be spaces\\otr.bat" ["<arg0>" ["<arg1>" ...]]')
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
您只是忘了将其设置为原始字符串。问题出在 \ 字符上。在路径前添加 r 将解决此问题 :)
import os
os.system(r"D:\xxx1\xxx2XMLnew\otr.bat")
以下是我在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)
python_test.py
import subprocess
a = subprocess.check_output("batch_1.bat")
print a
batch_1.bat
echo off
echo "Hello World"
md newdir
echo "made new directory"
bat
文件中调用另一个exe
文件,
您必须在所调用的bat
文件中使用SET Path
。
set Path 应该指向exe
文件所在的目录:set PATH=C:\;C:\DOS {Sets C:\;C:\DOS as the current search path.}
import os
os.startfile("filename.bat")
os.startfile("filename.bat")
os.startfile("filename2.bat")
os.chdir("X:\directory_inwhich_the_code_will_run")
os.system("D:\\xxx1\\xxx2XMLnew\\otr.bat ")
- inspectorG4dget尝试:
import os
os.system(r"D:\xxx1\xxx2XMLnew\otr.bat ")
- Md Fantacher Islam