Python静默执行命令行语句

大多数情况,用Python执行cmd命令的时候是用os.system(command)。

但有的时候,不想让控制台输出日志。

这时我会用subprocess的run函数。

1
2
from subprocess import run, DEVNULL
run(command, stdout=DEVNULL, stderr=DEVNULL, shell=True)

用的时候设置好command就行了。

stdout和stderr分别是标准输出和标准错误。

这俩参数和DEVNULL可以看我之前的这篇博客:

一些基础符号

如果想保存日志,将stdout和stderr的值分别设置好:open(file,"w")。