簡體   English   中英

如何從 python 靜默運行批處理文件 (.bat) 或命令?

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

如何從 python 運行批處理文件而不回顯?

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

預期結果:

doing command
finished command

結果:

doing command
Some command results
finished command

我嘗試使用 os.system 而不是批處理文件,但結果相同。

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

注意:使用 cmd /k,“完成的命令”不顯示

您應該使用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

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

編輯:如果您對進程的 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