将批处理文件输出管道输出到Python脚本

时间:2009-05-08 22:41:22

标签: python windows scripting batch-file io

我正在尝试编写一个运行批处理文件的python脚本(在Windows中),并将该批处理文件的命令行输出作为输入。批处理文件运行我无权访问的进程,并根据这些进程是否成功提供输出。我想从批处理文件中获取这些消息并在python脚本中使用它们。任何人对如何做到这一点都有任何想法?

3 个答案:

答案 0 :(得分:8)

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”启动批处理文件。

答案 1 :(得分:2)

这是一个示例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"

答案 2 :(得分:1)

尝试subprocess.Popen()。它允许您将stdout和stderr重定向到文件。

相关问题