目 录CONTENT

文章目录
ACM

Python 进阶 - 执行系统命令

解小风
2024-12-25 / 0 评论 / 1 点赞 / 27 阅读 / 2211 字
# subprocess.run(cmd, shell=True, capture_output=True, text=True)
# 功能:执行系统命令 (python3.5+)
# 输入:
#       cmd: {str} 系统命令(windows DOS 命令 或 linux shell 命令)
#       shell: {bool} 是否通过系统终端执行命令
#           shell=True 命令是字符串且包含终端特定功能(如管道、重定向等)
#       capture_output: {bool} 是否捕获标准输出和标准错误
#           capture_output=True 可通过 stdout 和 stderr 属性来获取命令的输出
#       text: {bool} 是否将输出作为 字符串 而不是 字节序列 返回
# 输出:
#       cmd_result: {CompletedProcess} 包含属性如下:
#           returncode: 命令退出状态。returncode=0 则命令执行成功;其他值则命令执行失败
#           stdout: 标准输出
#           stderr: 标准错误
# -*- coding: utf-8 -*-
import os
import subprocess

def execute_command(cmd):
    """
    # 功能:执行系统命令
    """
    cmd_result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
    return cmd_result.stdout.strip()

def change_directory(directory):
    """
    # 功能:跳转到指定目录
    """
    os.chdir(directory)


if __name__ == "__main__":

    # windows:DOS 命令
    cur_path = r"D:\PythonWorks"
    cur_cmd = f"dir {cur_path}"
    print( f"[INFO] cur_command: {cur_cmd}" )

    # linux:shell 命令
    cur_directory = "/home/faramita"
    change_directory(cur_directory)
    cur_path = "./tools"
    cur_cmd = f"ls -p {cur_path} | grep -v / | wc -l"
    # cur_text = "这里是标准测试"
    # cur_cmd = f"./build/bin/tts_main --spk cancan --text '{cur_text}'"
    print( f"[INFO] cur_command: {cur_cmd}" )

    # 执行命令
    cur_result = execute_command(cur_cmd)
    print( f"[INFO] cur_result: {cur_result}" )

1
  1. 支付宝打赏

    qrcode alipay
  2. 微信打赏

    qrcode weixin

评论区