赞
踩
点击上方分类专栏、进行系统性学习(文末可扫码领取资料)
- subprocess.run(args, *, stdin=None, input=None, stdout=None, stderr=None,
- capture_output=False, shell=False, cwd=None, timeout=None,
- check=False, encoding=None, errors=None, text=None, env=None,
- universal_newlines=None)
args
:要执行的命令。必须是一个字符串或字符串参数列表stdin
、stdout
和stderr
:子进程的标准输入、输出和错误。其值可以是subprocess.PIPE
、subprocess.DEVNULL
、一个已经存在的文件描述符、已经打开的文件对象或者 None(默认,表示什么都不做)。stderr 可以合并到 stdout 里一起输出subprocess.PIPE
表示为子进程创建新的管道subprocess.DEVNULL
表示使用os.devnull
timeout
:设置命令超时时间。如果命令执行时间超时,子进程将被杀死,并弹出 TimeoutExpired 异常check
:如果该参数设置为 True,并且进程退出状态码不是 0,则弹出 CalledProcessError 异常encoding
:如果指定了该参数,则 stdin、stdout 和 stderr 可以接收字符串数据,并以该编码方式编码。否则只接收 bytes 类型的数据shell
:如果该参数为 True,将通过操作系统的 shell 执行指定的命令CompletedProcess
实例,和直接Popen
差不多,实现是一样的(实际也是调用 Popen,与 Popen 构造函数大致相同)- import subprocess
-
- # 执行 ``ls -l /dev/null`` 命令;
- # 执行后, 会在终端输出: crw-rw-rw- 1 root root 1, 3 Apr 26 2022 /dev/null
- res = subprocess.run(["ls", "-l", "/dev/null"])
-
- # jy: CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0)
- # returncode 记录执行完子进程状态, 为 0 则表明它已经运行完毕, 若值为负值 "-N", 表明
- # 子进程被终;
- print(res)
-
-
-
- def runcmd(command):
- ret = subprocess.run(command, shell=True,
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
- encoding="utf-8", timeout=1)
- if ret.returncode == 0:
- print("success:",ret)
- else:
- print("error:",ret)
-
- # jy: 假设当前文件夹中有两个文件: test.py 和 test.py
- runcmd(["ls","-a"]) # 序列参数
- """
- success: CompletedProcess(args=['ls', '-a'], returncode=0, stdout='test.py\ntest.py\n', stderr='')
- """
-
- runcmd("exit 1") # 字符串参数
- """
- error: CompletedProcess(args='exit 1', returncode=1, stdout='', stderr='')
- """
- class subprocess.Popen(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=False,
- startupinfo=None, creationflags=0,restore_signals=True,
- start_new_session=False, pass_fds=(), *, encoding=None,
- errors=None)
args
:shell 命令,可以是字符串或者序列类型(如:list,元组)bufsize
:缓冲区大小。当创建标准流的管道对象时使用,默认 -1universal_newlines=True
时(即文本模式)可用stdin
、stdout
、stderr
:分别表示程序的标准输入、输出、错误句柄preexec_fn
:只在 Unix 平台下有效,用于指定一个可执行对象(callable object),它将在子进程运行之前被调用shell
:是否通过操作系统的 shell 执行指定的命令cwd
:设置子进程的当前目录env
:指定子进程的环境变量。如果env = None
,子进程的环境变量将从父进程中继承- import subprocess
-
- # 创建一个子进程并执行简单命令
- p = subprocess.Popen('ls -l', shell=True)
- #p = subprocess.Popen(['ls', '-cl'])
-
- print("-" * 66)
- print(p)
- print("-" * 66)
- print(p.returncode)
- print("-" * 66)
- print(p.wait())
- print("-" * 66)
- print(p.returncode)
-
- """
- ------------------------------------------------------------------
- <Popen: returncode: None args: 'ls -l'>
- ------------------------------------------------------------------
- None
- ------------------------------------------------------------------
- total 4
- -rw-r--r-- 1 root root 192 Feb 1 10:09 test.py
- -rw-r--r-- 1 root root 0 Feb 1 08:19 tmpFile
- 0
- ------------------------------------------------------------------
- 0
- """
poll()
:检查进程是否终止,如果终止返回 returncode,否则返回 Nonewait(timeout)
:等待子进程终止communicate(input, timeout)
:和子进程交互,发送和读取数据send_signal(singnal)
:发送信号到子进程terminate()
:停止子进程(发送SIGTERM
信号到子进程)kill()
:杀死子进程(发送SIGKILL
信号到子进程)- import time
- import subprocess
-
- def cmd(command):
- subp = subprocess.Popen(command, shell=True,
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
- encoding="utf-8")
- subp.wait(2)
- if subp.poll() == 0:
- print(subp)
- print(subp.communicate())
- else:
- print("失败")
-
- cmd("perl -v")
- """
- <Popen: returncode: 0 args: 'perl -v'>
- ('\nThis is perl 5, version 26, subversion 3 (v5.26.3) built for x86_64-linux-thread-multi\n(with 55 registered patches, see perl -V for more detail)\n\nCopyright 1987-2018, Larry Wall\n\nPerl may be copied only under the terms of either the Artistic License or the\nGNU General Public License, which may be found in the Perl 5 source kit.\n\nComplete documentation for Perl, including FAQ lists, should be found on\nthis system using "man perl" or "perldoc perl". If you have access to the\nInternet, point your browser at http://www.perl.org/, the Perl Home Page.\n\n', '')
- """
-
- cmd("exit 1")
- """
- 失败
- """
subprocess.check_output
函数可以执行一条 shell 命令,并返回命令的输出内容(Run command with arguments and return its output.)。- subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, cwd=None,
- encoding=None, errors=None, universal_newlines=None,
- timeout=None, text=None, **other_popen_kwargs)
CalledProcessError
. The CalledProcessError
object will have the return code in the returncode
attribute and any output in the output
attribute.CalledProcessError
:subprocess — Subprocess management — Python 3.12.2 documentationrun(..., check=True, stdout=PIPE).stdout
- import subprocess
-
- # jy: 默认返回结果为 bytes 形式;
- output = subprocess.check_output(["ls", "-a"], shell = False)
- # jy: b'.\n..\ntest.py\n'
- print(output)
- # jy: <class 'bytes'>
- print(type(output))
-
-
- # jy: 设置编码, 使得输出结果为字符串形式;
- output = subprocess.check_output(["ls", "-a"], shell = False, encoding="utf8")
- #output = subprocess.check_output(["ls", "-a"], shell = False, encoding="UTF-8")
- # jy: '.\n..\ntest.py\n', 输出时会被换行输出如下:
- """
- .
- ..
- test.py
- """
- print(output)
- # jy: <class 'str'>
- print(type(output))
- # jy: ['.', '..', 'test.py', '']
- print(output.split("\n"))
融码一生:专注 Python、Linux、C/C++、机器学习 & 深度学习 & NLP 领域创作
下方扫码关注公众号,获取完整 PDF / 线上电子书
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。