网络编程
位置:首页>> 网络编程>> Python编程>> python运行cmd命令行的3种方法总结

python运行cmd命令行的3种方法总结

作者:幸福的达哥  发布时间:2023-07-15 18:40:49 

标签:Python,运行,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

补充: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)     #写入文件

来源:https://blog.csdn.net/zh6526157/article/details/121775954

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com