Python/Subprocess_Module

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_39591494/article/details/89460466

Python/subprocess_module


The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. This module intends to replace several older modules and functions:
子流程模块允许生成新流程,连接到它们的输入/输出/错误管道,并获得它们的返回代码。本模块拟替换几个较老的模块和功能:

The recommended approach to invoking subprocesses is to use the run() function for all use cases it can handle. For more advanced use cases, the underlying Popen interface can be used directly.

 The recommended approach to invoking subprocesses is to use the run() function for all use cases it can handle. For more advanced use cases, the underlying Popen interface can be used directly.
run()函数是在Python 3.5中添加的, 以上为官方述,此篇文章将带你掌握subprocess基本用法。 start…

一、使用subprocess操作命令


两个必须要掌握的方法:

  • run
  • Popen

几个常见的重要参数:

  • stdout
  • encoding
  • check
  • shell

取控制台结果:

  • stdout
  • communicate()

subprocess可以理解为,通过python中的subprocess类中的方法如:run Popen对Linux操作系统进行操作,并将操作返回,接下来将一一介绍subprocess中的方法以及参数的使用,包括如何取到控制台结果。

1.1、subprocess.run

subprocess.run(args, *, stdin=None, input=None, stdout=None, stderr=None, shell=False, cwd=None, timeout=None, check=False, encoding=None, errors=None, env=None)

Run the command described by args. Wait for command to complete, then return a CompletedProcess instance.(运行args描述的命令。等待命令完成,然后返回一个CompletedProcess实例。),也就是subprocess.run(“写入args:Linux命令”) 返回一个CompletedProcess实例。

In [2]: importsubprocess                                                                                                                                                   

In [3]: subprocess.run("ls") # run(Linux命令)                                                                                                                                             
anaconda-ks.cfg miniconda3 Miniconda3-latest-Linux-x86_64.sh	nginx-1.12.2 nginx-1.12.2.tar.gz tcp_socket.py udp_socket.py yankai.txt yankerp_data
Out[3]: CompletedProcess(args='ls', returncode=0)

在这里插入图片描述

以上返回的内容为:CompletedProcess(args='ls', returncode=0) args:操作的命令。 returncode为状态码:0

扫描二维码关注公众号,回复: 5993388 查看本文章

在上面所说:stdout为取结果,那么将subprocess.run(“ls”) 赋值给一个对象result 通过result.stdout 取结果试试,如下:
在这里插入图片描述
通过测试发现当result = subprocess.run(“ls”) 运行时,结果直接输出,在result.stdout取结果时为None,接下来将介绍subprocess.run() 方法中的几个参数:stdout、encoding、shell、check

1.1.1、 shell

  shell参数可以理解为可以解析Linux命令,也就是让subprocess.run(args) 中的args能够正常执行Linux命令。一张图一个测试即可理解。如下:
在这里插入图片描述

异常:FileNotFoundError: [Errno 2] No such file or directory: ‘df -h’: ‘df -h’

那么不加shell=True参数可以吗? 当然。如下:
在这里插入图片描述

格式:subprocess.run([“ls”, “-l”]) or subprocess.run([“df”, “-h”])

1.1.2、 stdout

Captured stdout from the child process. A bytes sequence, or a string if run() was called with an encoding or errors. None if stdout was not captured.Captured stdout from the child process. A bytes sequence, or a string if run() was called with an encoding or errors. None if stdout was not captured.(它可以取到一个标准输出的结果,结果类型为字节流,如果在参数中定义encoding,就可以返回字符串)。一张图即可理解stdout作用。如下:
在这里插入图片描述
以上:result = subprocess.run("df -h", shell=True, stdout=subprocess.PIPE)可以理解为,通过subprocess.run(“df -h”)的结果通过PIPE管道—传给—>stdout。最后赋值给result对象 result为自定义。最后通过result.stdout 就可以取到值了。

1.1.3、 encoding

在以上的结果可以发现它是一串字节流的形式,通过\n换行,在stdout中提过通过encoding参数可以对结果进行字符串的转换。如下:
在这里插入图片描述
输出结果为\n换行,不要紧,可以通过splitlines()将每行输出
在这里插入图片描述

1.1.4、 check

If check is true, and the process exits with a non-zero exit code, a CalledProcessError exception will be raised. Attributes of that exception hold the arguments, the exit code, and stdout and stderr if they were captured.(如果检查为真,并且进程以非零的退出代码退出,则会引发一个名为processerror异常。)如下:
在这里插入图片描述

In [59]: Fdisk = subprocess.run("df -h", shell=True, stdout=subprocess.PIPE, encoding="utf-8", check=True)                                                                             

In [60]: Fdisk.stdout.splitlines()                                                                                                                                                     
Out[60]: 
['Filesystem               Size  Used Avail Use% Mounted on',
 '/dev/mapper/centos-root   50G  2.5G   48G   5% /',
 'devtmpfs                 903M     0  903M   0% /dev',
 'tmpfs                    913M     0  913M   0% /dev/shm',
 'tmpfs                    913M  8.6M  904M   1% /run',
 'tmpfs                    913M     0  913M   0% /sys/fs/cgroup',
 '/dev/mapper/centos-home  146G   33M  146G   1% /home',
 '/dev/sda1                497M  125M  373M  26% /boot',
 'tmpfs                    183M     0  183M   0% /run/user/0']
2.1、Subprocess.Popen

通过上面的subprocess.run操作后,其实subprocess.Popen和run很相似。 运行一条命令如下:
在这里插入图片描述

2.1.1、定义stdout

只需要一张图理解:
在这里插入图片描述

定义一个函数使用subprocess.Popen

In [54]: def get_data(cmd): 
    ...:     result = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) 
    ...:     data = result.stdout.read().decode().splitlines() 
    ...:     return data 
    ...:                                                                                                                                                                               

In [55]: get_data("df -h")                                                                                                                                                             
Out[55]: 
['Filesystem               Size  Used Avail Use% Mounted on',
 '/dev/mapper/centos-root   50G  2.5G   48G   5% /',
 'devtmpfs                 903M     0  903M   0% /dev',
 'tmpfs                    913M     0  913M   0% /dev/shm',
 'tmpfs                    913M  8.6M  904M   1% /run',
 'tmpfs                    913M     0  913M   0% /sys/fs/cgroup',
 '/dev/mapper/centos-home  146G   33M  146G   1% /home',
 '/dev/sda1                497M  125M  373M  26% /boot',
 'tmpfs                    183M     0  183M   0% /run/user/0']

In [56]: 

Warning: Use communicate() rather than .stdin.write, .stdout.read or .stderr.read to avoid deadlocks due to any of the other OS pipe buffers filling up and blocking the child process.

在使用Popen时通过communicate() 取结果
communicate() returns a tuple (stdout_data, stderr_data). The data will be strings if streams were opened in text mode; otherwise, bytes.

格式:

proc = subprocess.Popen(...)
try:
    outs, errs = proc.communicate(timeout=15)
except TimeoutExpired:
    proc.kill()
    outs, errs = proc.communicate()

通过communicate() 取结果:

In [62]: def get_data(cmd): 
    ...:     proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, encoding="utf-8") 
    ...:     try: 
    ...:         outs, errors = proc.communicate(timeout=15) 
    ...:         return outs.splitlines() 
    ...:     except TimeoutExpired: 
    ...:         proc.kill() 
    ...:                                                                                                                                                                               

In [63]: get_data("df -h")                                                                                                                                                             
Out[63]: 
['Filesystem               Size  Used Avail Use% Mounted on',
 '/dev/mapper/centos-root   50G  2.5G   48G   5% /',
 'devtmpfs                 903M     0  903M   0% /dev',
 'tmpfs                    913M     0  913M   0% /dev/shm',
 'tmpfs                    913M  8.6M  904M   1% /run',
 'tmpfs                    913M     0  913M   0% /sys/fs/cgroup',
 '/dev/mapper/centos-home  146G   33M  146G   1% /home',
 '/dev/sda1                497M  125M  373M  26% /boot',
 'tmpfs                    183M     0  183M   0% /run/user/0']

In [64]:  

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_39591494/article/details/89460466
今日推荐