常用模块学习(五)

  • 常用模块学习—configparser模块详解

    • 用于生成和修改常见配置文档,在Python2中是大写ConfigParser。

import configparser                        #在Python2中是大写ConfigParser      导入模块

conf = configparser.ConfigParser()          #实例化(生成对象)
#print(conf.sections())                     #调用sections方法

conf.read("conf.ini")                     # 读配置文件(注意文件路径)

#调用sections方法(默认不会读取default)
print(conf.sections())                      #每一个配置文件里都有一个DEFAULT    结果为:['bitbucket.org', 'topsecret.server.com']
print(conf.default_section)                 #结果为:DEFAULT       单独列出

#print(dir(conf["bitbucket.org"]))
#结果为:['_MutableMapping__marker', '__abstractmethods__', '__class__', '__contains__',
#  '__delattr__', '__delitem__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__',
# '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__module__', '__ne__', '__new__',
# '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__setattr__', '__setitem__', '__sizeof__', '__slots__', '__str__',
#  '__subclasshook__', '__weakref__', '_abc_impl', '_name', '_options', '_parser', 'clear', 'get', 'getboolean', 'getfloat', 'getint',
#  'items', 'keys', 'name', 'parser', 'pop', 'popitem', 'setdefault', 'update', 'values']

#print(list(conf["bitbucket.org"].keys()))          #结果为:['user', 'serveraliveinterval', 'compression', 'compressionlevel', 'forwardx11']
#print(conf["bitbucket.org"]['User'])               #结果为:hg


# for循环 bitbucket.org 字典的key
for k in conf["bitbucket.org"]:
    print(k)
#结果为:
# user
# serveraliveinterval
# compression
# compressionlevel
# forwardx11

for k,v in conf["bitbucket.org"].items():
    print(k,v)
#结果为:
# user hg
# serveraliveinterval 45
# compression yes
# compressionlevel 9
# forwardx11 yes


#判断有没有这个参数
if 'sss' in conf["bitbucket.org"]:
    print('in')                         #结果为:

if 'user' in conf["bitbucket.org"]:
    print('in')                         #结果为:in
[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes

[bitbucket.org]
User = hg

[topsecret.server.com]
Port = 50022
ForwardX11 = no
conf.ini
import configparser                        #在Python2中是大写ConfigParser      导入模块

conf = configparser.ConfigParser()          #实例化(生成对象)

conf.read("conf_test.ini")


#
print(dir(conf))
#结果为:['BOOLEAN_STATES', 'NONSPACECRE', 'OPTCRE', 'OPTCRE_NV', 'SECTCRE', '_DEFAULT_INTERPOLATION', '_MutableMapping__marker',
#  '_OPT_NV_TMPL', '_OPT_TMPL', '_SECT_TMPL', '__abstractmethods__', '__class__', '__contains__', '__delattr__', '__delitem__',
#  '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__',
#  '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__',
#  '__reduce_ex__', '__repr__', '__reversed__', '__setattr__', '__setitem__', '__sizeof__', '__slots__', '__str__', '__subclasshook__',
# '__weakref__', '_abc_impl', '_allow_no_value', '_comment_prefixes', '_convert_to_boolean', '_converters', '_defaults', '_delimiters',
#  '_dict', '_empty_lines_in_values', '_get', '_get_conv', '_handle_error', '_inline_comment_prefixes', '_interpolation', '_join_multiline_values',
#  '_optcre', '_proxies', '_read', '_read_defaults', '_sections', '_strict', '_unify_values', '_validate_value_types', '_write_section', 'add_section',
#  'clear', 'converters', 'default_section', 'defaults', 'get', 'getboolean', 'getfloat', 'getint', 'has_option', 'has_section', 'items', 'keys', 'options',
# 'optionxform', 'pop', 'popitem', 'read', 'read_dict', 'read_file', 'read_string', 'readfp', 'remove_option', 'remove_section', 'sections', 'set', 'setdefault',
#  'update', 'values', 'write']

#获取指定section的keys
print(conf.options("group1"))              #结果为:['k1', 'k2']

#获取指定 section 的 keys & values ,key value 以元组的形式
print(conf.items("group1"))              #结果为:[('k1', 'v1'), ('k2', 'v2')]

#获取指定的key 的value
print(conf['group1']['k2'])               #结果为:v2



#
conf.add_section("group3")
conf['group3']['name'] = "Alex Li"
conf['group3']['age'] = '22'

conf.write(open('conf_test.ini','w'))


#删除
conf.remove_option("group2",'age')
conf.write(open('conf_test.ini',"w"))

conf.remove_section("group1")
conf.write(open('conf_test.ini',"w"))
[group1]
k1 = v1
k2 = v2

[group2]
k1 = v1
age = 23
conf_test.ini

 

  • 常用模块学习—hashlib加密模块详解

    • HASH

                  Hash,一般翻译做“散列”,也有直接音译为”哈希”的,就是把任意长度的输入(又叫做预映射,pre-image),通过散列算法,变换成固定长度的输出,该输出就是散列值。这种转换是一种压缩映射,也就是,散列值的空间通常远小于输入的空间,不同的输入可能会散列成相同的输出,而不可能从散列值来唯一的确定输入值。

                 简单的说就是一种将任意长度的消息压缩到某一固定长度的消息摘要的函数。

                 HASH主要用于信息安全领域中加密算法,他把一些不同长度的信息转化成杂乱的128位的编码里,叫做HASH值.也可以说,hash就是找到一种数据内容和数据存放地址之间的映射关系。

    • MD5

                      什么是MD5算法?

                             MD5讯息摘要演算法(英语:MD5 Message-Digest Algorithm),一种被广泛使用的密码杂凑函数,可以产生出一个128位的散列值(hash value),用于确保信息传输完整一致。MD5的前身有MD2、MD3和MD4。

                       MD5功能:

                            输入任意长度的信息,经过处理,输出为128位的信息(数字指纹);
                           不同的输入得到的不同的结果(唯一性);

                       MD5算法的特点:

      1. 压缩性:任意长度的数据,算出的MD5值的长度都是固定的
      2. 容易计算:从原数据计算出MD5值很容易
      3. 抗修改性:对原数据进行任何改动,修改一个字节生成的MD5值区别也会很大
      4. 强抗碰撞:已知原数据和MD5,想找到一个具有相同MD5值的数据(即伪造数据)是非常困难的。 

                      MD5算法是否可逆?

                              MD5不可逆的原因是其是一种散列函数,使用的是hash算法,在计算过程中原文的部分信息是丢失了的。

                      MD5用途:

    • 防止被篡改:
      • 比如发送一个电子文档,发送前,我先得到MD5的输出结果a。然后在对方收到电子文档后,对方也得到一个MD5的输出结果b。如果a与b一样就代表中途未被篡改。

      • 比如我提供文件下载,为了防止不法分子在安装程序中添加木马,我可以在网站上公布由安装文件得到的MD5输出结果。

      • SVN在检测文件是否在CheckOut后被修改过,也是用到了MD5.

    • 防止直接看到明文:
      • 现在很多网站在数据库存储用户的密码的时候都是存储用户密码的MD5值。这样就算不法分子得到数据库的用户密码的MD5值,也无法知道用户的密码。(比如在UNIX系统中用户的密码就是以MD5(或其它类似的算法)经加密后存储在文件系统中。当用户登录的时候,系统把用户输入的密码计算成MD5值,然后再去和保存在文件系统中的MD5值进行比较,进而确定输入的密码是否正确。通过这样的步骤,系统在并不知道用户密码的明码的情况下就可以确定用户登录系统的合法性。这不但可以避免用户的密码被具有系统管理员权限的用户知道,而且还在一定程度上增加了密码被破解的难度。)
    • 防止抵赖(数字签名):
      • 这需要一个第三方认证机构。例如A写了一个文件,认证机构对此文件用MD5算法产生摘要信息并做好记录。若以后A说这文件不是他写的,权威机构只需对此文件重新产生摘要信息,然后跟记录在册的摘要信息进行比对,相同的话,就证明是A写的了。这就是所谓的“数字签名”。

 

    • SHA-1

                    安全哈希算法(Secure Hash Algorithm)主要适用于数字签名标准(Digital Signature Standard DSS)里面定义的数字签名算法(Digital Signature Algorithm DSA)。对于长度小于2^64位的消息,SHA1会产生一个160位的消息摘要。当接收到消息的时候,这个消息摘要可以用来验证数据的完整性。

                   SHA是美国国家安全局设计的,由美国国家标准和技术研究院发布的一系列密码散列函数。

                  由于MD5和SHA-1于2005年被山东大学的教授王小云破解了,科学家们又推出了SHA224, SHA256, SHA384, SHA512,当然位数越长,破解难度越大,但同时生成加密的消息摘要所耗时间也更长。目前最流行的是加密算法是SHA-256 .

    • MD5与SHA-1的比较

                   由于MD5与SHA-1均是从MD4发展而来,它们的结构和强度等特性有很多相似之处。

                  SHA-1与MD5的最大区别在于其摘要比MD5摘要长32 比特。

                 对于强行攻击,产生任何一个报文使之摘要等于给定报文摘要的难度:MD5是2128数量级的操作,SHA-1是2160数量级的操作。

                 产生具有相同摘要的两个报文的难度:MD5是264是数量级的操作,SHA-1 是280数量级的操作。

                 因而,SHA-1对强行攻击的强度更大。但由于SHA-1的循环步骤比MD5多80:64且要处理的缓存大160比特:128比特,SHA-1的运行速度比MD5慢。

#哈希值(在当前程序下,多数情况是唯一的,但也有重复的可能)
print(hash('alex'))                         #结果为:6244811259811791660

#哈希值的字符长度
print(len(str(hash('alex'))))               #结果为:20
print(20*8)                                  #结果为:160


#MD5(永远不会变,是唯一的值)
print(128/8)                                 #结果为:16.0

#演示
import hashlib
m = hashlib.md5()
m.update(b'alex')
print(m.hexdigest())                         #结果为:534b44a19bf18d20b71ecc4eb77c572f
print(len(m.hexdigest()))                    #结果为:32
print(len(m.hexdigest())*4)                  #结果为:128

m2 = hashlib.md5()
m.update(b'alex^&$')
print(m.hexdigest())                         #结果为:d95ad86fc47335ad6176d54c83d6a74c

MD5在线解密破解: http://www.cmd5.com/

 

 

  • CentOS7.X下安装Python3

#CentOS7.X下安装Python3

[root@wuqianqian-learn ~]# yum install epel-release -y
Loaded plugins: fastestmirror
base                                                                                                                                                                                                                 | 3.6 kB  00:00:00     
epel                                                                                                                                                                                                                 | 3.2 kB  00:00:00     
extras                                                                                                                                                                                                               | 3.4 kB  00:00:00     
nginx                                                                                                                                                                                                                | 2.9 kB  00:00:00     
updates                                                                                                                                                                                                              | 3.4 kB  00:00:00     
(1/3): extras/7/x86_64/primary_db                                                                                                                                                                                    | 147 kB  00:00:00     
(2/3): epel/x86_64/primary                                                                                                                                                                                           | 3.5 MB  00:00:00     
(3/3): epel/x86_64/updateinfo                                                                                                                                                                                        | 933 kB  00:00:00     
Loading mirror speeds from cached hostfile
 * base: mirrors.aliyun.com
 * epel: mirrors.aliyun.com
 * extras: mirrors.aliyun.com
 * updates: mirrors.aliyun.com
epel                                                                                                                                                                                                                            12584/12584
Resolving Dependencies
--> Running transaction check
---> Package epel-release.noarch 0:7-11 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

============================================================================================================================================================================================================================================
 Package                                                       Arch                                                    Version                                                  Repository                                             Size
============================================================================================================================================================================================================================================
Installing:
 epel-release                                                  noarch                                                  7-11                                                     epel                                                   15 k

Transaction Summary
============================================================================================================================================================================================================================================
Install  1 Package

Total download size: 15 k
Installed size: 24 k
Downloading packages:
epel-release-7-11.noarch.rpm                                                                                                                                                                                         |  15 kB  00:00:00     
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
  Installing : epel-release-7-11.noarch                                                                                                                                                                                                 1/1 
warning: /etc/yum.repos.d/epel.repo created as /etc/yum.repos.d/epel.repo.rpmnew
  Verifying  : epel-release-7-11.noarch                                                                                                                                                                                                 1/1 

Installed:
  epel-release.noarch 0:7-11                                                                                                                                                                                                                

Complete!
[root@iZqmo9i3j77p7eZ ~]# yum install https://centos7.iuscommunity.org/ius-release.rpm -y
Loaded plugins: fastestmirror
ius-release.rpm                                                                                                                                                                                                      | 8.1 kB  00:00:00     
Examining /var/tmp/yum-root-c8qWEb/ius-release.rpm: ius-release-1.0-15.ius.centos7.noarch
Marking /var/tmp/yum-root-c8qWEb/ius-release.rpm to be installed
Resolving Dependencies
--> Running transaction check
---> Package ius-release.noarch 0:1.0-15.ius.centos7 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

============================================================================================================================================================================================================================================
 Package                                                 Arch                                               Version                                                          Repository                                                Size
============================================================================================================================================================================================================================================
Installing:
 ius-release                                             noarch                                             1.0-15.ius.centos7                                               /ius-release                                             8.5 k

Transaction Summary
============================================================================================================================================================================================================================================
Install  1 Package

Total size: 8.5 k
Installed size: 8.5 k
Downloading packages:
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
  Installing : ius-release-1.0-15.ius.centos7.noarch                                                                                                                                                                                    1/1 
  Verifying  : ius-release-1.0-15.ius.centos7.noarch                                                                                                                                                                                    1/1 

Installed:
  ius-release.noarch 0:1.0-15.ius.centos7                                                                                                                                                                                                   

Complete!
[root@wuqianqian-learn ~]# yum install python36u -y
Loaded plugins: fastestmirror
ius                                                                                                                                                                                                                  | 2.3 kB  00:00:00     
ius/x86_64/primary_db                                                                                                                                                                                                | 250 kB  00:00:00     
Loading mirror speeds from cached hostfile
 * base: mirrors.aliyun.com
 * epel: mirrors.aliyun.com
 * extras: mirrors.aliyun.com
 * ius: mirrors.tuna.tsinghua.edu.cn
 * updates: mirrors.aliyun.com
Resolving Dependencies
--> Running transaction check
---> Package python36u.x86_64 0:3.6.5-1.ius.centos7 will be installed
--> Processing Dependency: python36u-libs(x86-64) = 3.6.5-1.ius.centos7 for package: python36u-3.6.5-1.ius.centos7.x86_64
--> Processing Dependency: libpython3.6m.so.1.0()(64bit) for package: python36u-3.6.5-1.ius.centos7.x86_64
--> Running transaction check
---> Package python36u-libs.x86_64 0:3.6.5-1.ius.centos7 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

============================================================================================================================================================================================================================================
 Package                                                     Arch                                                Version                                                             Repository                                        Size
============================================================================================================================================================================================================================================
Installing:
 python36u                                                   x86_64                                              3.6.5-1.ius.centos7                                                 ius                                               57 k
Installing for dependencies:
 python36u-libs                                              x86_64                                              3.6.5-1.ius.centos7                                                 ius                                              8.7 M

Transaction Summary
============================================================================================================================================================================================================================================
Install  1 Package (+1 Dependent package)

Total download size: 8.8 M
Installed size: 40 M
Downloading packages:
warning: /var/cache/yum/x86_64/7/ius/packages/python36u-3.6.5-1.ius.centos7.x86_64.rpm: Header V4 DSA/SHA1 Signature, key ID 9cd4953f: NOKEY
Public key for python36u-3.6.5-1.ius.centos7.x86_64.rpm is not installed
(1/2): python36u-3.6.5-1.ius.centos7.x86_64.rpm                                                                                                                                                                      |  57 kB  00:00:00     
(2/2): python36u-libs-3.6.5-1.ius.centos7.x86_64.rpm                                                                                                                                                                 | 8.7 MB  00:00:00     
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Total                                                                                                                                                                                                        16 MB/s | 8.8 MB  00:00:00     
Retrieving key from file:///etc/pki/rpm-gpg/IUS-COMMUNITY-GPG-KEY
Importing GPG key 0x9CD4953F:
 Userid     : "IUS Community Project <coredev@iuscommunity.org>"
 Fingerprint: 8b84 6e3a b3fe 6462 74e8 670f da22 1cdf 9cd4 953f
 Package    : ius-release-1.0-15.ius.centos7.noarch (installed)
 From       : /etc/pki/rpm-gpg/IUS-COMMUNITY-GPG-KEY
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
  Installing : python36u-libs-3.6.5-1.ius.centos7.x86_64                                                                                                                                                                                1/2 
  Installing : python36u-3.6.5-1.ius.centos7.x86_64                                                                                                                                                                                     2/2 
  Verifying  : python36u-3.6.5-1.ius.centos7.x86_64                                                                                                                                                                                     1/2 
  Verifying  : python36u-libs-3.6.5-1.ius.centos7.x86_64                                                                                                                                                                                2/2 

Installed:
  python36u.x86_64 0:3.6.5-1.ius.centos7                                                                                                                                                                                                    

Dependency Installed:
  python36u-libs.x86_64 0:3.6.5-1.ius.centos7                                                                                                                                                                                               

Complete!
[root@wuqianqian-learn ~]# ln -s /bin/python3.6 /bin/python3
[root@wuqianqian-learn ~]# yum install python36u-pip -y
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
 * base: mirrors.aliyun.com
 * epel: mirrors.aliyun.com
 * extras: mirrors.aliyun.com
 * ius: mirrors.tongji.edu.cn
 * updates: mirrors.aliyun.com
Resolving Dependencies
--> Running transaction check
---> Package python36u-pip.noarch 0:9.0.1-1.ius.centos7 will be installed
--> Processing Dependency: python36u-setuptools for package: python36u-pip-9.0.1-1.ius.centos7.noarch
--> Running transaction check
---> Package python36u-setuptools.noarch 0:39.0.1-1.ius.centos7 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

============================================================================================================================================================================================================================================
 Package                                                          Arch                                               Version                                                          Repository                                       Size
============================================================================================================================================================================================================================================
Installing:
 python36u-pip                                                    noarch                                             9.0.1-1.ius.centos7                                              ius                                             1.8 M
Installing for dependencies:
 python36u-setuptools                                             noarch                                             39.0.1-1.ius.centos7                                             ius                                             642 k

Transaction Summary
============================================================================================================================================================================================================================================
Install  1 Package (+1 Dependent package)

Total download size: 2.4 M
Installed size: 13 M
Downloading packages:
(1/2): python36u-setuptools-39.0.1-1.ius.centos7.noarch.rpm                                                                                                                                                          | 642 kB  00:00:00     
(2/2): python36u-pip-9.0.1-1.ius.centos7.noarch.rpm                                                                                                                                                                  | 1.8 MB  00:00:00     
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Total                                                                                                                                                                                                       4.7 MB/s | 2.4 MB  00:00:00     
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
  Installing : python36u-setuptools-39.0.1-1.ius.centos7.noarch                                                                                                                                                                         1/2 
  Installing : python36u-pip-9.0.1-1.ius.centos7.noarch                                                                                                                                                                                 2/2 
  Verifying  : python36u-setuptools-39.0.1-1.ius.centos7.noarch                                                                                                                                                                         1/2 
  Verifying  : python36u-pip-9.0.1-1.ius.centos7.noarch                                                                                                                                                                                 2/2 

Installed:
  python36u-pip.noarch 0:9.0.1-1.ius.centos7                                                                                                                                                                                                

Dependency Installed:
  python36u-setuptools.noarch 0:39.0.1-1.ius.centos7                                                                                                                                                                                        

Complete!
[root@wuqianqian-learn ~]# ln -s /bin/pip3.6 /bin/pip3
[root@wuqianqian-learn ~]# python3
Python 3.6.5 (default, Apr 10 2018, 17:08:37) 
[GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] on linux
Type "help", "copyright", "credits" or "license" for more information.

 

  • 常用模块学习—subprocess模块详解

    • 要通过Python去执行一条系统命令或脚本,系统的shell命令是独立于你的python进程之外的,每执行一条命令,就是发起一个新进程,通过python调用系统命令或脚本的模块在python2有os.system。

      >>> os.system('uname -a')
      Darwin Alexs-MacBook-Pro.local 15.6.0 Darwin Kernel Version 15.6.0: Sun Jun  4 21:43:07 PDT 2017; root:xnu-3248.70.3~1/RELEASE_X86_64 x86_64
      0

      这条命令的实现原理是什么呢?(视频中讲,解释进程间通信的问题...)

      除了os.system可以调用系统命令,,commands,popen2等也可以,比较乱,于是官方推出了subprocess,目地是提供统一的模块来实现对系统命令或脚本的调用。

                 子流程模块允许您生成新的进程,连接到它们的输入/输出/错误管道,并获得它们的返回码。这个模块打算替换几个较老的模块和功能:

                      os.system

                     os.spawn *

                调用子流程的推荐方法是使用run()函数来处理它所能处理的所有用例。对于更高级的用例,底层的Popen接口可以直接使用。

                run()函数在python3.5中添加;如果您需要保持与旧版本的兼容性,请参阅较旧的高级API部分

    • 三种执行命令的方法

      • subprocess.run(*popenargs, input=None, timeout=None, check=False, **kwargs)          #官方推荐

      • subprocess.call(*popenargs, timeout=None, **kwargs)                 #跟上面实现的内容差不多,另一种写法

      • subprocess.Popen()             #上面各种方法的底层封装

    • run()方法

                    用参数运行命令并返回一个完整的流程实例。返回的实例将具有属性args、returncode、stdout和stderr。

                    默认情况下,stdout和stderr没有被捕获,这些属性将是None。通过stdout=管道和/或stderr=管道来捕获它们。

                   如果检查是正确的,并且出口代码是非零的,那么它就会产生一个称为processerror。

                   processerror对象将在returncode属性中拥有退货代码,如果捕捉到这些流,则输出&stderr属性。

                   如果超时,并且进程花费的时间太长,将会抛出一个超时过期的异常。

                   其他的参数与Popen构造函数是一样的。

 标准写法:

subprocess.run(['df','-h'],stderr=subprocess.PIPE,stdout=subprocess.PIPE,check=True)

 

涉及到管道|的命令需要这样写:

subprocess.run('df -h|grep disk1',shell=True) #shell=True的意思是这条命令直接交给系统去执行,不需要python负责解析

 

subprocess.run()方法:

[root@wuqianqian-learn ~]# python3
>>> import subprocess
>>> subprocess.run(['df','-h'])
Filesystem      Size  Used Avail Use% Mounted on
/dev/vda1        40G  2.1G   36G   6% /
devtmpfs        911M     0  911M   0% /dev
tmpfs           920M     0  920M   0% /dev/shm
tmpfs           920M  340K  920M   1% /run
tmpfs           920M     0  920M   0% /sys/fs/cgroup
tmpfs           184M     0  184M   0% /run/user/0
CompletedProcess(args=['df', '-h'], returncode=0)

>>> a = subprocess.run(['df','-h'])
Filesystem      Size  Used Avail Use% Mounted on
/dev/vda1        40G  2.1G   36G   6% /
devtmpfs        911M     0  911M   0% /dev
tmpfs           920M     0  920M   0% /dev/shm
tmpfs           920M  340K  920M   1% /run
tmpfs           920M     0  920M   0% /sys/fs/cgroup
tmpfs           184M     0  184M   0% /run/user/0

>>> a
CompletedProcess(args=['df', '-h'], returncode=0)
>>> a.stdout.read()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'read'

>>> a.returncode

>>> a.args
['df', '-h']

>>> a.check_returncode()

>>> a = subprocess.run(['df','-h'],stdout=subprocess.PIPE,stderr=subprocess.PIPE)

>>> a.stdout
b'Filesystem      Size  Used Avail Use% Mounted on\n/dev/vda1        40G  2.1G   36G   6% /\ndevtmpfs        911M     0  911M   0% /dev\ntmpfs           920M     0  920M   0% /dev/shm\ntmpfs           920M  340K  920M   1% /run\ntmpfs           920M     0  920M   0% /sys/fs/cgroup\ntmpfs           184M     0  184M   0% /run/user/0\n'

>>> a.stderr
b''

>>> a = subprocess.run(['df','-fdsfh'],stdout=subprocess.PIPE,stderr=subprocess.PIPE)

>>> a.stdout
b''
>>> a.stderr
b"df: invalid option -- 'f'\nTry 'df --help' for more information.\n"

>>> a = subprocess.run(['df','-fdsfh'],stdout=subprocess.PIPE,stderr=subprocess.PIPE,check=True)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python3.6/subprocess.py", line 418, in run
    output=stdout, stderr=stderr)
subprocess.CalledProcessError: Command '['df', '-fdsfh']' returned non-zero exit status 1.

>>> a = subprocess.run(['df','-fdsfh'],stdout=subprocess.PIPE,stderr=subprocess.PIPE,check=True)
KeyboardInterrupt

>>> exit()

[root@wuqianqian-learn ~]# df 
Filesystem     1K-blocks    Used Available Use% Mounted on
/dev/vda1       41151808 2199444  36838932   6% /
devtmpfs          932240       0    932240   0% /dev
tmpfs             941748       0    941748   0% /dev/shm
tmpfs             941748     340    941408   1% /run
tmpfs             941748       0    941748   0% /sys/fs/cgroup
tmpfs             188352       0    188352   0% /run/user/0

[root@wuqianqian-learn ~]# df -h |grep vda1
/dev/vda1        40G  2.1G   36G   6% /
[root@wuqianqian-learn ~]# 
[root@wuqianqian-learn ~]# 
[root@wuqianqian-learn ~]# python3

>>> a = subprocess.run(['df','-h','|','grep','vda1'],stdout=subprocess.PIPE,stderr=subprocess.PIPE,check=True)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'subprocess' is not defined

>>> import subprocess
>>> a.stdout.read()     
KeyboardInterrupt
>>> a = subprocess.run(['df','-h','|','grep','vda1'],stdout=subprocess.PIPE,stderr=subprocess.PIPE,check=True)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python3.6/subprocess.py", line 418, in run
    output=stdout, stderr=stderr)
subprocess.CalledProcessError: Command '['df', '-h', '|', 'grep', 'vda1']' returned non-zero exit status 1.

>>> a = subprocess.run(['df','-h','|','grep','vda1'],stdout=subprocess.PIPE,stderr=subprocess.PIPE)           
>>> a.stderr
b'df: \xe2\x80\x98|\xe2\x80\x99: No such file or directory\ndf: \xe2\x80\x98grep\xe2\x80\x99: No such file or directory\ndf: \xe2\x80\x98vda1\xe2\x80\x99: No such file or directory\n'
>>> a = subprocess.run('df -h |grep vda1',stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)