脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|shell|

服务器之家 - 脚本之家 - Python - python运行cmd命令10种方式并获得返回值的高级技巧

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

2024-03-19 15:05《代码爱好者》   Python

这篇文章主要给大家介绍了关于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命令获得返回值内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/zh6526157/article/details/135643737

延伸 · 阅读

精彩推荐
  • PythonPython二分查找+字符串模板+textwrap模块

    Python二分查找+字符串模板+textwrap模块

    这篇文章主要介绍了Python二分查找+字符串模板+textwrap模块,文章围绕主题展开详细内容,具有一定的参考价值,需要的小伙伴可以参考一下...

    梦想橡皮擦10972023-02-02
  • Python浅析python函数式编程

    浅析python函数式编程

    这篇文章主要介绍了python函数式编程的相关资料,帮助大家更好的理解和使用python,感兴趣的朋友可以了解下...

    程序猿-悟空5362020-09-26
  • PythonPython Json模块中dumps、loads、dump、load函数介绍

    Python Json模块中dumps、loads、dump、load函数介绍

    本篇文章主要介绍了Python Json模块中dumps、loads、dump、load函数介绍,详细的介绍了这几种函数的用法,具有一定的参考价值,感兴趣的小伙伴们可以参考一...

    Mr_EvanChen15112021-02-21
  • Python将Django使用的数据库从MySQL迁移到PostgreSQL的教程

    将Django使用的数据库从MySQL迁移到PostgreSQL的教程

    这篇文章主要介绍了将Django使用的数据库从MySQL迁移到PostgreSQL的教程,同时提到了一些注意事项,需要的朋友可以参考下 ...

    calazan5732020-06-03
  • Pythonpython 的赋值语句和基本输入输出详解

    python 的赋值语句和基本输入输出详解

    这篇文章主要为大家介绍了python 赋值语句和基本输入输出,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助...

    暮色年华_5592022-03-11
  • Pythonpython获取微信小程序手机号并绑定遇到的坑

    python获取微信小程序手机号并绑定遇到的坑

    这篇文章主要介绍了python获取微信小程序手机号并绑定遇到的坑,本文给大家介绍的非常详细,具有一定的参考借鉴价值 ,需要的朋友可以参考下...

    如何好听6622021-04-21
  • PythonPython中22个万用公式的小结

    Python中22个万用公式的小结

    在大家的日常python程序的编写过程中,都会有自己解决某个问题的解决办法,或者是在程序的调试过程中,用来帮助调试的程序公式,本文总结了22个万用...

    J519LEE7262021-12-14
  • PythonPython3爬虫全国地址信息

    Python3爬虫全国地址信息

    今天小编就为大家分享一篇关于Python3爬虫全国地址信息,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看...

    只是个宝宝11722021-05-12