将批处理文件输出传递给Python脚本
我正在尝试写一个Python脚本(在Windows系统上),这个脚本需要运行一个批处理文件,并把这个批处理文件的命令行输出作为输入。这个批处理文件会运行一些我无法直接访问的程序,并根据这些程序是否成功来输出信息。我想把批处理文件里的这些消息拿到Python脚本中使用。有没有人知道怎么做到这一点?
3 个回答
1
试试使用 subprocess.Popen()。这个方法可以让你把输出信息和错误信息保存到文件里。
3
下面是一个示例的Python脚本,它会运行test.bat文件并显示输出结果:
import os
fh = os.popen("test.bat")
output = fh.read()
print "This is the output of test.bat:", output
fh.close()
test.bat文件的内容如下:
@echo off
echo "This is test.bat"
9
import subprocess
output= subprocess.Popen(
("c:\\bin\\batch.bat", "an_argument", "another_argument"),
stdout=subprocess.PIPE).stdout
for line in output:
# do your work here
output.close()
注意,最好在你的批处理文件开头加上“@echo off
”。