Piping Batch File output to a Python script

牧云@^-^@ 提交于 2019-12-12 14:14:14

问题


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 ?


回答1:


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".




回答2:


Here is a sample python script that runs test.bat and displays the output:

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:

@echo off
echo "This is test.bat"



回答3:


Try subprocess.Popen(). It allows you to redirect stdout and stderr to files.



来源:https://stackoverflow.com/questions/842120/piping-batch-file-output-to-a-python-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!