python运行cmd命令行

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

python运行cmd命令行

幸福的达哥   2022-09-29 我要评论

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

补充:python调用cmd进行输入输出

由于程序需要用java和python混用,所以可以取巧,就是在python中调用cmd,在cmd中执行java
所以,进行了一下测试。完美运行

import os

with open("text1.txt","w",encoding="utf8") as file1:
    mystr = os.popen("ipconfig")  # popen与system可以执行指令,popen可以接受返回对象
    mystr = mystr.read()  # 读取输出
    file1.write(mystr)     #写入文件

总结

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们