python|3种运行cmd命令行的方法
1.执行cmd命令,不显示执行过程中弹出的黑框
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.执行cmd命令,并得到执行后的返回值,python调试界面输出返回值
def run_cmd_Popen_fileno(cmd_string):
"""
执行cmd命令,并得到执行后的返回值,python调试界面输出返回值
:param cmd_string: cmd命令,如:'adb devices'
:return:
"""
import subprocess
print('运行cmd指令:{}'.format(cmd_string))
return subprocess.Popen(cmd_string, shell=True, stdout=None, stderr=None).wait()
3.执行cmd命令,并得到执行后的返回值,python调试界面不输出返回值
def run_cmd_Popen_PIPE(cmd_string):
"""
执行cmd命令,并得到执行后的返回值,python调试界面不输出返回值
:param cmd_string: cmd命令,如:'adb devices"'
: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='gbk').communicate()[0]
调用方法
if __name__ == '__main__':
run_cmd_run('adb devices')
run_cmd_Popen_fileno('adb devices')
run_cmd_Popen_PIPE('adb devices')
执行结果
执行cmd指令="adb devices" List of devices attached 3356caad?? ?device
运行cmd指令:adb devices List of devices attached 3356caad?? ?device
运行cmd指令:adb devices
今日美图






如果你觉得文章还不错,请?点赞、评论、收藏、关注?,下期内容很快更新。?
|