首页 > 其他分享 >【6.0】常用模块之subprocess模块

【6.0】常用模块之subprocess模块

时间:2023-11-25 21:23:41浏览次数:23  
标签:None shell 模块 stdout subprocess stderr 6.0 进程

【一】介绍

  • subprocess模块允许我们启动一个新进程,并连接到它们的输入/输出/错误管道,从而获取返回值。
  • 简单理解就是:使用我们自己的电脑去链接别人的电脑 (socket模块)

【二】使用

【1】导入模块

import subprocess

【2】简单使用

# windows系统默认的编码格式是:gbk
import subprocess

"""
    1. 使用我们自己的电脑去链接别人的电脑 (socket模块)
"""
res = subprocess.Popen('tasklistaaa', shell=True,
                       stdout=subprocess.PIPE,
                       stderr=subprocess.PIPE
                       )

print(res)  # <subprocess.Popen object at 0x000001ABB1970310>
# print(res.stdout.read().decode('gbk'))  # tasklist执行之后的正确结果返回
print(res.stderr.read().decode('gbk'))
  • subprocess模块首先推荐使用的是它的run方法,
  • 更高级的用法可以直接使用Popen接口。

【三】run方法

def run(*popenargs,
        input=None, capture_output=False, timeout=None, check=False, **kwargs):
  • args

    • 表示要执行的命令。
    • 必须是一个字符串,字符串参数列表。
  • stdinstdoutstderr

    • 子进程的标准输入、标准输出和标准错误。

      • 其值可以是subprocess.PIPE

        • subprocess.PIPE 表示为子进程创建新的管道。
      • subprocess.DEVNULL

        • subprocess.DEVNULL表示使用 os.devnull
          • 默认使用的是 None,表示什么都不做。
      • 一个已经存在的文件描述符、

      • 已经打开的文件对象

      • 或者 None。

    • 另外

      • stderr 可以合并到 stdout 里一起输出。
  • timeout:

  • 设置命令超时时间。

  • 如果命令执行时间超过timeout,

  • 子进程将被杀死,并弹出 TimeoutExpired 异常。

  • check

    • 如果该参数设置为 True,并且进程退出状态码不是0
    • 则弹出 CalledProcessError 异常。
  • encoding:

    • 如果指定了该参数,则 stdinstdoutstderr 可以接收字符串数据,并以该编码方式编码。
    • 否则只接收 bytes 类型的数据。
  • shell

    • 如果该参数为 True
    • 将通过操作系统的shell执行指定的命令。

【1】示例

import os
import subprocess

BASE_DIR = os.path.dirname(os.path.dirname(__file__))
print(BASE_DIR)
# Use "dir" on Windows and "ls" on Unix-like systems
command = "dir" if os.name == "nt" else "ls"

# 该run()函数只传入了一个参数,而且该参数是以列表的形式传入的。
res = subprocess.run([command, BASE_DIR], capture_output=True, text=True)
print(res.stdout)

【2】示例

import subprocess


def runcmd(command):
    ret = subprocess.run(command,  # 子进程要执行的命令
                         shell=True,  # 执行的是shell的命令
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE,
                         encoding="utf-8",
                         timeout=1)

    # returncode属性是run()函数返回结果的状态。
    if ret.returncode == 0:
        print("success:", ret)
    else:
        print("error:", ret)


runcmd(["dir", "/b"])  # 序列参数
# success: CompletedProcess(args=['dir', '/b'], returncode=0, stderr='')
runcmd("exit 1")  # 字符串参数
# error: CompletedProcess(args='exit 1', returncode=1, stdout='', stderr='')

【四】Popen方法

【1】介绍

  • Popen 是 subprocess的核心,子进程的创建和管理都靠它处理。
class Popen:
    """ Execute a child program in a new process.

    For a complete description of the arguments see the Python documentation.

    Arguments:
      args: A string, or a sequence of program arguments.

      bufsize: supplied as the buffering argument to the open() function when
          creating the stdin/stdout/stderr pipe file objects

      executable: A replacement program to execute.

      stdin, stdout and stderr: These specify the executed programs' standard
          input, standard output and standard error file handles, respectively.

      preexec_fn: (POSIX only) An object to be called in the child process
          just before the child is executed.

      close_fds: Controls closing or inheriting of file descriptors.

      shell: If true, the command will be executed through the shell.

      cwd: Sets the current directory before the child is executed.

      env: Defines the environment variables for the new process.

      text: If true, decode stdin, stdout and stderr using the given encoding
          (if set) or the system default otherwise.

      universal_newlines: Alias of text, provided for backwards compatibility.

      startupinfo and creationflags (Windows only)

      restore_signals (POSIX only)

      start_new_session (POSIX only)

      group (POSIX only)

      extra_groups (POSIX only)

      user (POSIX only)

      umask (POSIX only)

      pass_fds (POSIX only)

      encoding and errors: Text mode encoding and error handling to use for
          file objects stdin, stdout and stderr.

    Attributes:
        stdin, stdout, stderr, pid, returncode
    """
    _child_created = False  # Set here since __del__ checks it

    def __init__(self, args, bufsize=-1, executable=None,
                 stdin=None, stdout=None, stderr=None,
                 preexec_fn=None, close_fds=True,
                 shell=False, cwd=None, env=None, universal_newlines=None,
                 startupinfo=None, creationflags=0,
                 restore_signals=True, start_new_session=False,
                 pass_fds=(), *, user=None, group=None, extra_groups=None,
                 encoding=None, errors=None, text=None, umask=-1, pipesize=-1):
        ...
  • args:
    • shell命令,可以是字符串或者序列类型(如:list,元组)
  • bufsize:
    • 缓冲区大小。当创建标准流的管道对象时使用,
      • 默认是-1
      • 0代表不使用缓冲区
      • 1:表示行缓冲,仅当universal_newlines=True时可用,也就是文本模式
        • 正数:表示缓冲区大小
        • 负数:表示使用系统默认的缓冲区大小。
  • stdin, stdout, stderr:
    • 分别表示程序的标准输入、输出、错误句柄
  • preexec_fn:
    • 只在 Unix 平台下有效,用于指定一个可执行对象(callable object),它将在子进程运行之前被调用
  • shell:
    • 如果该参数为 True,将通过操作系统的 shell 执行指定的命令。
  • cwd:
    • 用于设置子进程的当前目录。
  • env:
    • 用于指定子进程的环境变量。
      • 如果 env = None,子进程的环境变量将从父进程中继承。
  • 创建一个子进程,然后执行一个简单的命令。

【2】示例

import subprocess

p = subprocess.Popen('ls -l', shell=True)


# Popen的对象所具有的方法:
#       poll(): 检查进程是否终止,如果终止则返回 returncode,否则返回 None。
#       wait(timeout): 等待子进程终止。
#       communicate(input,timeout): 和子进程交互,发送和读取数据。
#       send_signal(singnal): 发送信号到子进程 。
#       terminate(): 停止子进程,也就是发送SIGTERM信号到子进程。
#       kill(): 杀死子进程。发送 SIGKILL 信号到子进程。

def f(command):
    # 创建一个子进程,并且执行
    res_subprocess = subprocess.Popen(command,
                                      shell=True,
                                      stdout=subprocess.PIPE,
                                      stderr=subprocess.PIPE,
                                      encoding="utf-8")
    # 这里是用wait()方法,等待子进程结束。
    res_subprocess.wait(2)
    if res_subprocess.poll() == 0:
        print(res_subprocess.communicate()[1])
    else:
        print("失败")


f("python --version")
f("exit 1")

【五】call方法

【1】介绍

  • 调用subprocess.call()函数执行命令,将需要执行的命令以列表形式传递给该函数
def call(*popenargs, timeout=None, **kwargs):
    """Run command with arguments.  Wait for command to complete or
    timeout, then return the returncode attribute.

    The arguments are the same as for the Popen constructor.  Example:

    retcode = call(["ls", "-l"])
    """

【2】示例

import subprocess

subprocess.call(['python', '--version'])
# Python 3.10.10
  • 需要注意的是,在Linux或macOS系统上,可能需要使用sudo命令来获得管理员权限
import subprocess

subprocess.call(['sudo','python', '--version'])

标签:None,shell,模块,stdout,subprocess,stderr,6.0,进程
From: https://www.cnblogs.com/dream-ze/p/17856106.html

相关文章

  • 【5.0】常用模块之json、pickle模块
    【一】序列化和反序列化【1】什么是序列化将原本的字典、列表等内容转换成一个字符串的过程就叫做序列化。【2】为什么要有序列化比如,我们在python代码中计算的一个数据需要给另外一段程序使用,那我们怎么给?现在我们能想到的方法就是存在文件里然后另一个python程序再......
  • 课程模块
    06-01课程主页面之前台FreeCourse.vue<template><divclass="course"><Header></Header><divclass="main"><!--筛选条件--><divclass="condition">......
  • 【9.0】Python高级之常用模块学习
    【一】re【二】time、datetime【三】os......
  • 【2.0】常用模块之time、datetime模块
    【一】时间模块(time/datetime)【二】表示时间的三种方式在Python中,通常有这三种方式来表示时间:时间戳元组(struct_time)格式化的时间字符串:格式化的时间字符串(FormatString):‘1999-12-06’【三】time(1)导入时间模块importtime(2)时间戳(time)[1]生成时间戳......
  • 【1.0】常用模块之re模块
    【一】正则语法【1】引入一说规则我已经知道你很晕了现在就让我们先来看一些实际的应用。在线测试工具http://tool.chinaz.com/regex/首先你要知道的是谈到正则,就只和字符串相关了。在我给你提供的工具中,你输入的每一个字都是一个字符串。其次,如果在一个位置的一......
  • 【3.0】常用模块之os模块
    【一】文件操作(os)__file__是指当前文件【二】文件路径相关(path)(1)获取当前文件路径(abspath)importos#获取当前文件路径file_path=os.path.abspath(__file__)print(file_path)#E:\PythonProjects\07常用模块学习\03os模块.py(2)获取当前文件所在文件夹路径(dirn......
  • 聚合工程的微服务之创建父工程和子模块
    1、创建父工程创建一个普通的Maven项目,File》New》Project》MavenArchetype父级的pom文件只作项目子模块的整合,在maveninstall时不会生成jar/war压缩包。创建好后删除刚创建工程里不需要的文件,只保留:.idea 文件夹、项目 pom 文件,如果没有.gitignore文件,就在根目录下......
  • Python文件锁portalocker模块
    在多进程/多线程的学习后,终于来到了“文件锁”这个概念阶段,文件锁的存在就是由于在多进程/线程操作时会对某个文件进行频繁修改,而导致读取与修改的数据产生不同步。典型场景有以下:进程1对文件A进行写入操作,写入一条记录a,持续时间时20s才能完成这个文件的写入。此时进程2在第......
  • 【Django基础】auth认证模块
    https://www.cnblogs.com/DuoDuosg/p/17005583.html一、django的auth认证模块1.什么是auth模块Auth模块是Django自带的用户认证模块:我们在开发一个网站的时候,无可避免的需要设计实现网站的用户系统。此时我们需要实现包括用户注册、用户登录、用户认证、注销、修改密码等功能,......
  • KubeSphere 社区双周报 | Fluent Operator 2.6.0 发布 | 2023.11.10-11.23
    KubeSphere社区双周报主要整理展示新增的贡献者名单和证书、新增的讲师证书以及两周内提交过commit的贡献者,并对近期重要的PR进行解析,同时还包含了线上/线下活动和布道推广等一系列社区动态。本次双周报涵盖时间为:2023.11.10-2023.11.23。贡献者名单新晋KubeSphereCont......