简体   繁体   English

如何从 python 静默运行批处理文件 (.bat) 或命令?

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

How do I run a batch file from python without it echoing?如何从 python 运行批处理文件而不回显?

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.我尝试使用 os.system 而不是批处理文件,但结果相同。

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

Note: with cmd /k, "finished command" doesn't show注意:使用 cmd /k,“完成的命令”不显示

you should use either subprocess.getoutput or subprocess.Popen with stdout pointing to subprocess.PIPE , (and stderr pointing to either stdout or a pipe)您应该使用subprocess.getoutputsubprocess.Popen与 stdout 指向subprocess.PIPE ,(和 stderr 指向 stdout 或管道)

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使用Popen的好处是可以如下打开它作为上下文管理器,保证资源清理,还可以独立命令进程stdin,子进程不会阻塞你的python进程,简单来说它有更多用途比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.编辑:如果您对进程的 output 不感兴趣,则将其放入 devnull 是另一种选择,它只是将其丢弃。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM