cy614
cy614

Reputation: 61

How to run batch file (.bat) or command silently from python?

How do I run a batch file from python without it echoing?

print("doing command")
with open("batch.bat", "w") as f:
    f.write("@echo off\nsome_command")
subprocess.call(['batch.bat'])
input("finished command")

Expected result:

doing command
finished command

Result:

doing command
Some command results
finished command

I tried using os.system instead of the batch file but it's the same result.

print("doing command")
os.system('cmd /c "some_command"')
input("finished command")

Note: with cmd /k, "finished command" doesn't show

Upvotes: 0

Views: 1305

Answers (1)

Ahmed AEK
Ahmed AEK

Reputation: 17616

you should use either subprocess.getoutput or subprocess.Popen with stdout pointing to subprocess.PIPE, (and stderr pointing to either stdout or a pipe)

import subprocess
print("doing command")
with open("batch.bat", "w") as f:
    f.write("@echo off\nsome_command")
output = subprocess.getoutput('batch.bat')
input("finished command")
import subprocess
print("doing command")
with open("batch.bat", "w") as f:
    f.write("@echo off\nnsome_command")
process = subprocess.Popen('batch.bat',stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
output = process.stdout.read()
input("finished command")
doing command
finished command

the benefit of using Popen is that you can open it as a context manager as follows, which guarantee resources cleanup, and you can also command the process stdin independently, and the subprocess won't block your python process, put simply it has more uses than subprocess.getoutput

import subprocess
print("doing command")
with open("batch.bat", "w") as f:
    f.write("@echo off\nnsome_command")
with subprocess.Popen('batch.bat',stdout=subprocess.PIPE,stderr=subprocess.STDOUT) as process:
    output = process.stdout.read()
input("finished command")

Edit: if you are not interested in the output of the process, putting it into devnull is another option, it just discards it.

import subprocess
import os
print("doing command")
with open("batch.bat", "w") as f:
    f.write("@echo off\nnsome_command")
with open(os.devnull,'w') as null:
    process = subprocess.Popen('batch.bat',stdout=null,stderr=null)
input("finished command")

Upvotes: 2

Related Questions