视频加载失败

常用模块之subprocess模块

1364 字
7 分钟
常用模块之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:
    • 表示要执行的命令。
    • 必须是一个字符串,字符串参数列表。
  • stdin、stdout 和 stderr:
    • 子进程的标准输入、标准输出和标准错误。
      • 其值可以是subprocess.PIPE
        • subprocess.PIPE 表示为子进程创建新的管道。
      • subprocess.DEVNULL
        • subprocess.DEVNULL表示使用 os.devnull
          • 默认使用的是 None,表示什么都不做。
      • 一个已经存在的文件描述符、
      • 已经打开的文件对象
      • 或者 None。
    • 另外
      • stderr 可以合并到 stdout 里一起输出。
  • timeout:
  • 设置命令超时时间。
  • 如果命令执行时间超过timeout,
  • 子进程将被杀死,并弹出 TimeoutExpired 异常。
  • check:
    • 如果该参数设置为 True,并且进程退出状态码不是0
    • 则弹出 CalledProcessError 异常。
  • encoding:
    • 如果指定了该参数,则 stdin、stdout 和 stderr 可以接收字符串数据,并以该编码方式编码。
    • 否则只接收 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'])

支持与分享

如果这篇文章对你有帮助,欢迎分享给更多人或打赏支持!

打赏
Profile Image of the Author
Dream
Hello, I'm Dream.
公告
欢迎来到我的博客!爱学习爱进步。
分类
标签
最新动态
站点统计
文章
300
分类
5
标签
26
总字数
640,882
运行时长
0 天
最后活动
0 天前
站点信息
构建平台
Vercel
博客版本
Firefly v6.16.8
文章许可
CC BY-NC-SA 4.0
文章目录