Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?


2 Answers

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

like image 190
tzot Avatar answered Mar 08 '26 22:03

tzot


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"
like image 25
seddy Avatar answered Mar 08 '26 22:03

seddy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!