三种方式:
1.不显示执行过程中弹出的黑框
def run_cmd( cmd_str='', echo_print=1):
"""
执行cmd命令,不显示执行过程中弹出的黑框
备注:subprocess.run()函数会将本来打印到cmd上的内容打印到python执行界面上,所以避免了出现cmd弹出框的问题
:param cmd_str: 执行的cmd命令
:return:
"""
from subprocess import run
if echo_print == 1:
print('\n执行cmd指令="{}"'.format(cmd_str))
run(cmd_str, shell=True)
2.得到执行后的返回值,python调试界面输出返回值
def run_cmd_Popen_fileno(cmd_string):
"""
执行cmd命令,并得到执行后的返回值,python调试界面输出返回值
:param cmd_string: cmd命令,如:'nvcc -V'
:return:
"""
import subprocess
print('运行cmd指令:{}'.format(cmd_string))
return subprocess.Popen(cmd_string, shell=True, stdout=None, stderr=None).wait()
3.得到执行后的返回值,python调试界面不输出返回值
def run_cmd_Popen_PIPE(cmd_string):
"""
执行cmd命令,并得到执行后的返回值,python调试界面不输出返回值
:param cmd_string: cmd命令,如:'nvcc -V'
:return:
"""
import subprocess
print('运行cmd指令:{}'.format(cmd_string))
return subprocess.Popen(cmd_string, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding='utf-8').communicate()[0]
测试调用
if __name__ == '__main__':
run_cmd_run('nvcc -V')
run_cmd_Popen_fileno('nvcc -V')
run_cmd_Popen_PIPE('nvcc -V')
###结果###
执行cmd指令="nvcc -V"
nvcc: NVIDIA (R) Cuda compiler driver
Copyright (c) 2005-2019 NVIDIA Corporation
Built on Wed_Oct_23_21:14:42_PDT_2019
Cuda compilation tools, release 10.2, V10.2.89
运行cmd指令:=nvcc -V
nvcc: NVIDIA (R) Cuda compiler driver
Copyright (c) 2005-2019 NVIDIA Corporation
Built on Wed_Oct_23_21:14:42_PDT_2019
Cuda compilation tools, release 10.2, V10.2.89
运行cmd指令:nvcc -V