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

Question:

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 offnsome_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

Asked By: cy614

||

Answers:

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 offnsome_command")
output = subprocess.getoutput('batch.bat')
input("finished command")
import subprocess
print("doing command")
with open("batch.bat", "w") as f:
    f.write("@echo offnnsome_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 offnnsome_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 offnnsome_command")
with open(os.devnull,'w') as null:
    process = subprocess.Popen('batch.bat',stdout=null,stderr=null)
input("finished command")
Answered By: Ahmed AEK
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.