cmmacphe
cmmacphe

Reputation:

Piping Batch File output to a Python script

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 ?

Upvotes: 3

Views: 13019

Answers (3)

tzot
tzot

Reputation: 96011

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

Upvotes: 9

seddy
seddy

Reputation: 91

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"

Upvotes: 3

Don
Don

Reputation: 1169

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

Upvotes: 1

Related Questions