3

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 ?

3 Answers 3

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()

Note that it's preferable to start your batch file with "@echo off".

Sign up to request clarification or add additional context in comments.

Comments

3

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"

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.