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命令获得返回值内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Python3 SSH远程连接服务器的方法示例

    Python3 SSH远程连接服务器的方法示例

    这篇文章主要介绍了Python3 SSH远程连接服务器的方法示例,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-12-12
  • 详解Python中的内置常量的使用

    详解Python中的内置常量的使用

    Python作为一种功能强大的编程语言,提供了丰富的内置常量来简化编程过程,本文将深入探讨Python中的内置常量,并提供丰富的示例代码来演示其用法,希望对大家有所帮助
    2024-03-03
  • Python获取网段内ping通IP的方法

    Python获取网段内ping通IP的方法

    今天小编就为大家分享一篇Python获取网段内ping通IP的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-01-01
  • PyTorch实现更新部分网络,其他不更新

    PyTorch实现更新部分网络,其他不更新

    今天小编就为大家分享一篇PyTorch实现更新部分网络,其他不更新,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-12-12
  • Python中bs4的soup.find()和soup.find_all()用法示例小结

    Python中bs4的soup.find()和soup.find_all()用法示例小结

    我们在使用python对网页爬虫的时候,经常会得到一些html数据,因此我们就会利用soup.find()和soup.find_all()方法来筛选出想要的数据,这篇文章主要介绍了Python中bs4的soup.find()和soup.find_all()用法,需要的朋友可以参考下
    2024-12-12
  • Python脚本轻松实现检测麦克风功能

    Python脚本轻松实现检测麦克风功能

    在进行音频处理或开发需要使用麦克风的应用程序时,确保麦克风功能正常是非常重要的,本文将介绍一个简单的Python脚本,能够帮助我们检测本地麦克风的功能,需要的可以参考下
    2025-08-08
  • Python中的sort方法、sorted函数与lambda表达式及用法详解

    Python中的sort方法、sorted函数与lambda表达式及用法详解

    文章对比了Python中list.sort()与sorted()函数的区别,指出sort()原地排序返回None,sorted()生成新列表,本文结合实例代码给大家介绍的非常详细,感兴趣的朋友跟随小编一起看看吧
    2025-09-09
  • 使用Python 操作 xmind 绘制思维导图的详细方法

    使用Python 操作 xmind 绘制思维导图的详细方法

    在平时的工作中当我们要总结一些知识的时候就需要一款工具来画画流程图,这里推荐 XMind 软件,用 Xmind 绘制的思维导图看起来思路清晰,那么今天的文章介绍关于思维导图的相关知识以及用 Python 如何操作 Xmind 绘制思维导图
    2021-10-10
  • Ranorex通过Python将报告发送到邮箱的方法

    Ranorex通过Python将报告发送到邮箱的方法

    这篇文章主要介绍了Ranorex通过Python将报告发送到邮箱的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-01-01
  • 教你怎么用python实现字符串转日期

    教你怎么用python实现字符串转日期

    今天教各位小伙伴怎么用python实现字符串转日期,文中有非常详细的代码示例,对正在学习python的小伙伴很有帮助,需要的朋友可以参考下
    2021-05-05

最新评论