python运行cmd命令10种方式并获得返回值的高级技巧

 更新时间:2024年03月18日 11:14:40   作者:《代码爱好者》  
这篇文章主要给大家介绍了关于python运行cmd命令10种方式并获得返回值的高级技巧,主要包括python脚本执行CMD命令并返回结果的例子使用实例、应用技巧,文中通过代码介绍的非常详细,需要的朋友可以参考下

python10种方式运行cmd命令的高级技巧

import subprocess

# 方法1:使用subprocess模块的run函数
def run_cmd_1(command):
    """
    运行CMD命令并返回输出结果
    
    参数:
    command (str): 要执行的CMD命令
    
    返回:
    output (str): 命令执行的输出结果
    """
    try:
        result = subprocess.run(command, shell=True, capture_output=True, text=True)
        if result.returncode == 0:
            output = result.stdout.strip()
        else:
            output = result.stderr.strip()
    except Exception as e:
        output = str(e)
        
    return output

# 方法2:使用subprocess模块的check_output函数
def run_cmd_2(command):
    """
    运行CMD命令并返回输出结果
    
    参数:
    command (str): 要执行的CMD命令
    
    返回:
    output (str): 命令执行的输出结果
    """
    try:
        output = subprocess.check_output(command, shell=True, text=True)
        output = output.strip()
    except Exception as e:
        output = str(e)
        
    return output

# 方法3:使用os模块的system函数
def run_cmd_3(command):
    """
    运行CMD命令并返回输出结果
    
    参数:
    command (str): 要执行的CMD命令
    
    返回:
    output (str): 命令执行的输出结果
    """
    try:
        result = os.system(command)
        output = ""
        if result == 0:
            output = "命令执行成功"
        else:
            output = "命令执行失败"
    except Exception as e:
        output = str(e)
        
    return output

# 方法4:使用os模块的popen函数
def run_cmd_4(command):
    """
    运行CMD命令并返回输出结果
    
    参数:
    command (str): 要执行的CMD命令
    
    返回:
    output (str): 命令执行的输出结果
    """
    try:
        output = os.popen(command).read()
        output = output.strip()
    except Exception as e:
        output = str(e)
        
    return output

# 方法5:使用commands模块的getoutput函数
def run_cmd_5(command):
    """
    运行CMD命令并返回输出结果
    
    参数:
    command (str): 要执行的CMD命令
    
    返回:
    output (str): 命令执行的输出结果
    """
    try:
        output = commands.getoutput(command)
        output = output.strip()
    except Exception as e:
        output = str(e)
        
    return output

# 方法6:使用commands模块的getstatusoutput函数
def run_cmd_6(command):
    """
    运行CMD命令并返回输出结果
    
    参数:
    command (str): 要执行的CMD命令
    
    返回:
    output (str): 命令执行的输出结果
    """
    try:
        status, output = commands.getstatusoutput(command)
        output = output.strip()
    except Exception as e:
        output = str(e)
        
    return output

# 方法7:使用os模块的startfile函数
def run_cmd_7(command):
    """
    运行CMD命令并返回输出结果
    
    参数:
    command (str): 要执行的CMD命令
    
    返回:
    output (str): 命令执行的输出结果
    """
    try:
        os.startfile(command)
        output = "命令已启动"
    except Exception as e:
        output = str(e)
        
    return output

# 方法8:使用os模块的spawn函数
def run_cmd_8(command):
    """
    运行CMD命令并返回输出结果
    
    参数:
    command (str): 要执行的CMD命令
    
    返回:
    output (str): 命令执行的输出结果
    """
    try:
        output = os.spawnl(os.P_WAIT, 'cmd.exe', '/c', command)
        output = output.strip()
    except Exception as e:
        output = str(e)
        
    return output

# 方法9:使用win32api模块的ShellExecute函数
def run_cmd_9(command):
    """
    运行CMD命令并返回输出结果
    
    参数:
    command (str): 要执行的CMD命令
    
    返回:
    output (str): 命令执行的输出结果
    """
    try:
        win32api.ShellExecute(0, 'open', 'cmd.exe', '/c {}'.format(command), '', 0)
        output = "命令已启动"
    except Exception as e:
        output = str(e)
        
    return output

# 方法10:使用win32api模块的CreateProcess函数
def run_cmd_10(command):
    """
    运行CMD命令并返回输出结果
    
    参数:
    command (str): 要执行的CMD命令
    
    返回:
    output (str): 命令执行的输出结果
    """
    try:
        si = win32process.STARTUPINFO()
        si.dwFlags |= win32process.STARTF_USESHOWWINDOW
        output = win32api.CreateProcess(None, command, None, None, False, 0, None, None, si)[1].read()
        output = output.strip()
    except Exception as e:
        output = str(e)
        
    return output

# 示例:运行ipconfig命令获取网络配置信息
output = run_cmd_1('ipconfig')
print(output)

python12种方式运行cmd命令并获得返回值的高级技巧

import subprocess
import os
import commands
import win32api
import win32process

# 方法1:使用subprocess模块的run函数,返回CompletedProcess对象
def run_cmd_1(command):
    """
    运行CMD命令并返回CompletedProcess对象
    
    参数:
    command (str): 要执行的CMD命令
    
    返回:
    result (CompletedProcess): 命令执行的结果对象
    """
    try:
        result = subprocess.run(command, shell=True, capture_output=True, text=True)
    except Exception as e:
        result = str(e)
        
    return result

# 方法2:使用subprocess模块的check_output函数,返回命令的输出结果
def run_cmd_2(command):
    """
    运行CMD命令并返回输出结果
    
    参数:
    command (str): 要执行的CMD命令
    
    返回:
    output (bytes): 命令执行的输出结果
    """
    try:
        output = subprocess.check_output(command, shell=True)
    except Exception as e:
        output = str(e)
        
    return output

# 方法3:使用subprocess模块的call函数,返回命令的返回码
def run_cmd_3(command):
    """
    运行CMD命令并返回返回码
    
    参数:
    command (str): 要执行的CMD命令
    
    返回:
    returncode (int): 命令的返回码
    """
    try:
        returncode = subprocess.call(command, shell=True)
    except Exception as e:
        returncode = str(e)
        
    return returncode

# 方法4:使用subprocess模块的Popen函数,返回Popen对象
def run_cmd_4(command):
    """
    运行CMD命令并返回Popen对象
    
    参数:
    command (str): 要执行的CMD命令
    
    返回:
    process (Popen): Popen对象
    """
    try:
        process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    except Exception as e:
        process = str(e)
        
    return process

# 方法5:使用os模块的system函数,返回命令的返回码
def run_cmd_5(command):
    """
    运行CMD命令并返回返回码
    
    参数:
    command (str): 要执行的CMD命令
    
    返回:
    returncode (int): 命令的返回码
    """
    try:
        returncode = os.system(command)
    except Exception as e:
        returncode = str(e)
        
    return returncode

# 方法6:使用os模块的popen函数,返回命令的输出结果
def run_cmd_6(command):
    """
    运行CMD命令并返回输出结果
    
    参数:
    command (str): 要执行的CMD命令
    
    返回:
    output (str): 命令执行的输出结果
    """
    try:
        output = os.popen(command).read()
    except Exception as e:
        output = str(e)
        
    return output

# 方法7:使用commands模块的getoutput函数,返回命令的输出结果
def run_cmd_7(command):
    """
    运行CMD命令并返回输出结果
    
    参数:
    command (str): 要执行的CMD命令
    
    返回:
    output (str): 命令执行的输出结果
    """
    try:
        output = commands.getoutput(command)
    except Exception as e:
        output = str(e)
        
    return output

# 方法8:使用commands模块的getstatusoutput函数,返回命令的返回码和输出结果
def run_cmd_8(command):
    """
    运行CMD命令并返回返回码和输出结果
    
    参数:
    command (str): 要执行的CMD命令
    
    返回:
    status (int): 命令的返回码
    output (str): 命令执行的输出结果
    """
    try:
        status, output = commands.getstatusoutput(command)
    except Exception as e:
        status = str(e)
        output = ""
        
    return status, output

# 方法9:使用os模块的startfile函数,返回None
def run_cmd_9(command):
    """
    运行CMD命令
    
    参数:
    command (str): 要执行的CMD命令
    
    返回:
    None
    """
    try:
        os.startfile(command)
    except Exception as e:
        pass

# 方法10:使用os模块的spawn函数,返回命令的返回码
def run_cmd_10(command):
    """
    运行CMD命令并返回返回码
    
    参数:
    command (str): 要执行的CMD命令
    
    返回:
    returncode (int): 命令的返回码
    """
    try:
        returncode = os.spawnl(os.P_WAIT, 'cmd.exe', '/c', command)
    except Exception as e:
        returncode = str(e)
        
    return returncode

# 方法11:使用win32api模块的ShellExecute函数,返回None
def run_cmd_11(command):
    """
    运行CMD命令
    
    参数:
    command (str): 要执行的CMD命令
    
    返回:
    None
    """
    try:
        win32api.ShellExecute(0, 'open', 'cmd.exe', '/c {}'.format(command), '', 0)
    except Exception as e:
        pass

# 方法12:使用win32api模块的CreateProcess函数,返回命令的返回码和输出结果
def run_cmd_12(command):
    """
    运行CMD命令并返回返回码和输出结果
    
    参数:
    command (str): 要执行的CMD命令
    
    返回:
    returncode (int): 命令的返回码
    output (str): 命令执行的输出结果
    """
    try:
        si = win32process.STARTUPINFO()
        si.dwFlags |= win32process.STARTF_USESHOWWINDOW
        output = win32api.CreateProcess(None, command, None, None, False, 0, None, None, si)[1].read()
        returncode = 0
    except Exception as e:
        returncode = str(e)
        output = ""
        
    return returncode, output

# 示例:运行ipconfig命令获取网络配置信息,并获取返回值
result = run_cmd_1('ipconfig')
print(result.returncode)
print(result.stdout)

# 示例:运行dir命令获取文件列表,并获取输出结果
output = run_cmd_2('dir')
print(output)

# 示例:运行ping命令测试网络连接,并获取返回码
returncode = run_cmd_3('ping google.com')
print(returncode)

# 示例:运行tasklist命令获取进程列表,并获取Popen对象
process = run_cmd_4('tasklist')
print(process.stdout.readline())

# 示例:运行ipconfig命令获取网络配置信息,并获取返回码
returncode = run_cmd_5('ipconfig')
print(returncode)

# 示例:运行dir命令获取文件列表,并获取输出结果
output = run_cmd_6('dir')
print(output)

# 示例:运行ping命令测试网络连接,并获取输出结果
output = run_cmd_7('ping google.com')
print(output)

# 示例:运行tasklist命令获取进程列表,并获取返回码和输出结果
status, output = run_cmd_8('tasklist')
print(status)
print(output)

# 示例:运行notepad命令打开记事本应用程序
run_cmd_9('notepad')

# 示例:运行ping命令测试网络连接,并获取返回码
returncode = run_cmd_10('ping google.com')
print(returncode)

# 示例:运行notepad命令打开记事本应用程序
run_cmd_11('notepad')

# 示例:运行tasklist命令获取进程列表,并获取返回码和输出结果
returncode, output = run_cmd_12('tasklist')
print(returncode)
print(output)

总结 

到此这篇关于python运行cmd命令10种方式并获得返回值的文章就介绍到这了,更多相关python运行cmd命令获得返回值内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Python+Tkinter实现RGB数值转换为16进制码

    Python+Tkinter实现RGB数值转换为16进制码

    这篇文章主要为大家详细介绍了Python如何利用Tkinter编写一个RGB数值转换为16进制码的小工具,文中的示例代讲解详细,感兴趣的小伙伴可以了解一下
    2023-01-01
  • Python常见数据结构详解

    Python常见数据结构详解

    这篇文章主要介绍了Python常见数据结构,需要的朋友可以参考下
    2014-07-07
  • Python实现自动化发送邮件

    Python实现自动化发送邮件

    大家好,本篇文章主要讲的是Python实现自动化发送邮件,感兴趣的同学赶快来看一看吧,对你有帮助的话记得收藏一下
    2022-01-01
  • Python的pycurl包用法简介

    Python的pycurl包用法简介

    这篇文章主要介绍了Python的pycurl包用法简介,文中罗列了其下模块中的一些常用方法,需要的朋友可以参考下
    2015-11-11
  • Django 查询数据库返回JSON的实现

    Django 查询数据库返回JSON的实现

    和前端交互全部使用JSON,如何将数据库查询结果转换成JSON格式,本文就来介绍一下,感兴趣的小伙伴们可以参考一下
    2021-08-08
  • 如何搜索查找并解决Django相关的问题

    如何搜索查找并解决Django相关的问题

    每个程序员都会在开发过程中遇到这样或那样的问题, 有时光靠一个人是无法解决所有问题的, 所以我们应该找到适当的地方提问.
    2014-06-06
  • Python Web版语音合成实例详解

    Python Web版语音合成实例详解

    这篇文章主要介绍了Python Web版语音合成实例详解,语音合成技术能将用户输入的文字,转换成流畅自然的语音输出,并且可以支持语速、音调、音量设置,让人机沟通更自然,需要的朋友可以参考下
    2019-07-07
  • Numpy中的repeat函数使用

    Numpy中的repeat函数使用

    Numpy是Python强大的数学计算库,和Scipy一起构建起Python科学计算生态,在本节下面我们重点介绍下repeat函数的用法,需要的朋友可以参考下
    2022-11-11
  • Python实现调用jar或执行java代码的方法详解

    Python实现调用jar或执行java代码的方法详解

    这篇文章主要介绍了Python实现调用jar或执行java代码的方法,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-12-12
  • python django中8000端口被占用的解决

    python django中8000端口被占用的解决

    今天小编就为大家分享一篇python django中8000端口被占用的解决,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-12-12

最新评论