windows 管道批处理文件输出到 Python 脚本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/842120/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Piping Batch File output to a Python script
提问by tzot
I'm trying to write a python script (in windows) that runs a batch file and will take the command line output of that batch file as input. The batch file runs processes that I don't have access to and gives output based on whether those processes are successful. I'd like to take those messages from the batch file and use them in the python script. Anyone have any ideas on how to do this ?
我正在尝试编写一个运行批处理文件的 python 脚本(在 Windows 中),并将该批处理文件的命令行输出作为输入。批处理文件运行我无权访问的进程,并根据这些进程是否成功提供输出。我想从批处理文件中获取这些消息并在 python 脚本中使用它们。任何人对如何做到这一点有任何想法吗?
回答by tzot
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()
Note that it's preferable to start your batch file with "@echo off
".
请注意,最好以“ @echo off
”开头您的批处理文件。
回答by seddy
Here is a sample python script that runs test.bat and displays the output:
这是一个运行 test.bat 并显示输出的示例 python 脚本:
import os
fh = os.popen("test.bat")
output = fh.read()
print "This is the output of test.bat:", output
fh.close()
Source of test.bat:
test.bat的来源:
@echo off
echo "This is test.bat"
回答by Don
Try subprocess.Popen(). It allows you to redirect stdout and stderr to files.
尝试 subprocess.Popen()。它允许您将 stdout 和 stderr 重定向到文件。