首页 > 其他分享 >subprocess模块

subprocess模块

时间:2023-12-28 11:55:06浏览次数:19  
标签:None shell 模块 stdout subprocess stderr 进程

subprocess模块

(一)介绍

  • 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,进程
From: https://www.cnblogs.com/suyihang/p/17932405.html

相关文章

  • yum安装的nginx如何安装其他模块
    yum安装nginx没有某一模块,该如何添加第三方模块? 本文将以添加--with-stream模块为例,演示如何去添加新的模块进去。需求:生产有个接口是通过socket通信。nginx1.9开始支持tcp层的转发,通过stream实现的,而socket也是基于tcp通信。实现方法:Centos7.5下yum直接安装的nginx,添加新模......
  • 常用模块
    常用模块一、random模块[1]随机小数(1)默认区间的小数(random)在0和1之间的小数(可以取到0和1)importrandomres=random.random()print(res)#运行两次取到不同的值'''0.9791639451528830.3838093323775482'''(2)指定区间的小数(uniform)可以指定特定的区间importran......
  • webpack(模块modules 和 模块解析)
    模块(Modules)每个模块都具备了条理清晰的设计和明确的目的何为webpack模块与 Node.js模块相比,webpack模块能以各种方式表达它们的依赖关系。下面是一些示例:ES2015 import 语句CommonJS require() 语句AMD define 和 require 语句css/sass/less文件中的 @imp......
  • 11 ADC模块FEP-DAQ422X采集显示波形方案
    软件版本:VIVADO2021.1操作系统:WIN1064bit硬件平台:适用XILINXA7/K7/Z7/ZU/KU系列FPGA登录米联客(MiLianKe)FPGA社区-www.uisrc.com观看免费视频课程、在线答疑解惑!1概述本方案通过把DAQ422X采集到的数据,通过前面已经完成的示波器显示驱动进行在屏幕上显示ADC采集的波形数据......
  • 09 ADC模块FEP-DAQ7606采集显示波形方案
    软件版本:VIVADO2021.1操作系统:WIN1064bit硬件平台:适用XILINXA7/K7/Z7/ZU/KU系列FPGA登录米联客(MiLianKe)FPGA社区-www.uisrc.com观看免费视频课程、在线答疑解惑!1概述本方案通过把DAQ7606采集到的数据,通过前面已经完成的示波器显示驱动进行在屏幕上显示ADC采集的波形数......
  • 10 ADC模块FEP-DAQ9248采集显示波形方案
    软件版本:VIVADO2021.1操作系统:WIN1064bit硬件平台:适用XILINXA7/K7/Z7/ZU/KU系列FPGA登录米联客(MiLianKe)FPGA社区-www.uisrc.com观看免费视频课程、在线答疑解惑!1概述本方案通过把DAQ9248采集到的数据,通过示波器显示驱动进行在屏幕上显示ADC采集的波形数据。2系统框图......
  • 每日一模块:httpx解决http2
    #!/usr/bin/envpython#-*-coding:utf-8-*-#author:Cloud#datetime:2023/12/18importhttpx"""pipinstallhttpx[http2]-ihttp://mirrors.aliyun.com/pypi/simple/--trusted-hostmirrors.aliyun.com"""timeout=httpx.Time......
  • 如何快速还原Python内置模块的功能
    Python作为一门开源的编程语言,提供了丰富的内置模块和库,使开发者能够快速开发各种应用。然而,有时候我们可能在使用内置模块时不小心修改了其源代码,导致功能不正常或无法正常使用。本文将介绍如何快速还原Python内置模块的功能,以便恢复正常的开发环境。步骤一:确认问题首先,我们需要确......
  • Python windows下subprocess模块 cwd 参数不支持相对路径
    前言全局说明Pythonwindows下subprocess模块cwd参数不支持相对路径一、问题程序要执行命令,用到了subprocess模块,并指定了cwd运行路径,在MAC系统下运行正常,在Windows下运行报错。经过查询,是系统差异导致,所以为了方便,在windows下获取当前路径后拼接再生成绝对路径......
  • rebar3 引用本地elixir 模块
    前边简单说过基于rebar_mix使用elixir模块,但是使用的模块是三方的,如果时候我们可以需要使用自己的就可以使用本地git项目,或者搭建自己的私服git,以下是一个简单使用项目准备本地elixirmix项目一个基于mixcli创建的项目,同时进行gitinit mixnewlogingit......