python 3 (含subprocess模块)Chapter_2

 __init__ : 构造函数,在生成对象时调用(类的专有方法)该方法在类实例化时会自动调用,

#!/usr/bin/python3
 
class Complex:
    def __init__(self, realpart, imagpart):
        self.r = realpart
        self.i = imagpart
x = Complex(3.0, -4.5)
print(x.r, x.i)   # 输出结果:3.0 -4.5

 在类的内部,使用 def 关键字来定义一个方法,与一般函数定义不同,类方法必须包含参数 self, 且为第一个参数,self 代表的是类的实例。

#!/usr/bin/python3
 
#类定义
class people:
    #定义基本属性
    name = ''
    age = 0
    #定义私有属性,私有属性在类外部无法直接进行访问
    __weight = 0
    #定义构造方法
    def __init__(self,n,a,w):
        self.name = n
        self.age = a
        self.__weight = w
    def speak(self):
        print("%s 说: 我 %d 岁。" %(self.name,self.age))
 
# 实例化类
p = people('runoob',10,30)
p.speak()

 dataclass修饰器  python3.7引入

# 通常
class Number:
    def __init__(self, val):
        self.val = val
>>> one = Number(1)
>>> one.val
>>> 1

# dataclass:
@dataclass
class Number:
    val:int 
>>> one = Number(1)
>>> one.val
>>> 1

 Python内置的@property装饰器就是负责把一个方法变成属性调用的:

class Student(object):

    @property
    def score(self):
        return self._score

    @score.setter
    def score(self, value):
        if not isinstance(value, int):
            raise ValueError('score must be an integer!')
        if value < 0 or value > 100:
            raise ValueError('score must between 0 ~ 100!')
        self._score = value
>>> s = Student()
>>> s.score = 60 # OK,实际转化为s.set_score(60)
>>> s.score # OK,实际转化为s.get_score()
60
>>> s.score = 9999
Traceback (most recent call last):
  ...
ValueError: score must between 0 ~ 100!

 

Python模块导入时全局变量"__all__"的作用:

 在模块中的__all__变量就是为了限制或者指定能被导入到别的模块的函数,类,全局变量等,如果指定了那么只能是指定的那些可以被导入,没有指定默认就是全部可以导入,当然私有属性应该除外。如果去掉main.py的注释后,就会抛出错误。

 

Python3 字典 items() 方法:

Python 字典 items() 函数作用:以列表返回可遍历的(键, 值) 元组数组。


dict = {'老大':'15岁',

        '老二':'14岁',

        '老三':'2岁',

        '老四':'1岁'

        }

print(dict.items())

for key,values in dict.items():

    print(key + '已经' + values + '了')


dict_items([('老大', '15岁'), ('老二', '14岁'), ('老三', '2岁'), ('老四', '1岁')])

老大已经15岁了

老二已经14岁了

老三已经2岁了

老四已经1岁了

操纵类的模块方法:

attr.make_class:快速创建类

@attr.s(slots=True,frozen=True)  对应的方法分别为:相当于创建属性受限的类、创造在实例化后不可变的类。

attr.ib:是快速对属性进行定义的方法,其中有很多参数与attr.s的参数重合,可以在这里对每个属性进行特殊设置。

attr.fields_dict(cls):Return an ordered dictionary of attrs attributes for a class, whose keys are the attribute names.

Python super() 函数:是调用父类(超类)的一个方法。

字典方法:update() 方法,dict.update(dict2);items() 方法以列表返回可遍历的(键, 值) 元组数组,dict.items()

 

metadata:

利用特定转换程序对不同元数据元格式进行转换,称为元数据映射

元数据的定义:描述数据的数据(data about data),主要是描述数据属性(property)的信息,用来支持如指示存储位置、历史数据、资源查找、文件记录等功能。元数据算是一种电子式目录,为了达到编制目录的目的,必须在描述并收藏数据的内容或特色,进而达成协助数据检索的目的。


使用过数码相机的同学都应该知道,每张数码照片都会存在一个EXIF信息。它就是一种用来描述数码图片的元数据。根据EXIF标准,这些元数据包括:Image Description(图像描述、来源.
 指生成图像的工具 )、Artist(作者)、Make( 生产者)、Model (型号)、….、等等。

列表生成式:

# 对列表数平方

b = range(1, 11)
c = [x*x for x in b]
print(c)

# 结果:[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

 列表生成式语法是固定的,[]里面for 前面是对列表里面数据的运算操作,后面跟平常for循序一样遍历去读取。运行后会自动生成新的列表

Python中的__new__()方法:

依照Python官方文档的说法,__new__方法主要是当你继承一些不可变的class时(比如int, str, tuple), 提供给你一个自定义这些类的实例化过程的途径。还有就是实现自定义的metaclass。

class Singleton(object):
    def __new__(cls):
        # 关键在于这,每一次实例化的时候,我们都只会返回这同一个instance对象
        if not hasattr(cls, 'instance'):
            cls.instance = super(Singleton, cls).__new__(cls)
        return cls.instance

obj1 = Singleton()
obj2 = Singleton()

obj1.attr1 = 'value1'
print obj1.attr1, obj2.attr1
print obj1 is obj2

# 输出结果:
# value1 value1
# True  可以看到obj1和obj2是同一个实例。

 python assert的作用:

用来让程序测试这个condition,如果condition为false,那么raise一个AssertionError出来。逻辑上等同于:

if not condition:
    raise AssertionError()
Python3 zip() 函数:将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的对象,这样做的好处是节约了不少的内存。

 

 python3新特性函数注释Function Annotations

查看这些注释可以通过自定义函数的特殊属性__annotations__获取,结果会以字典的形式返回:

dog.__annotations__

# {'age': (1, 99), 'name': str, 'return': tuple, 'species': '狗狗的品种'}

https://docs.python.org/3.5/library/subprocess.html#subprocess.check_output

我们几乎可以在任何操作系统上通过命令行指令与操作系统进行交互

我们如何通过Python来完成这些命令行指令的执行呢?另外,我们应该知道的是命令行指令的执行通常有两个我们比较关注的结果:

  1. 命令执行的状态码--表示命令执行是否成功
  2. 命令执行的输出结果--命令执行成功后的输出

Popen.stdout

If the stdout argument was PIPE, this attribute is a readable stream object as returned by open(). Reading from the stream provides output from the child process. If the universal_newlines argument was True, the stream is a text stream, otherwise it is a byte stream. If the stdout argument was not PIPE, this attribute is None.

 

Using the subprocess Module

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 run() function was added in Python 3.5

Run the command described by args. Wait for command to complete, then return a CompletedProcess instance.

 

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.

exception subprocess.CalledProcessError

Subclass of SubprocessError, raised when a process run by check_call() or check_output() returns a non-zero exit status.

 

If the return code was non-zero it raises a CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute and any output in the output attribute.

This is equivalent to:

run(..., check=True, stdout=PIPE).stdout

 

Examples:

>>>>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], stdout=subprocess.PIPE)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n')

class subprocess.CompletedProcess

The return value from run(), representing a process that has finished.

 

stdout   Alias for output

Captured stdout from the child process. A bytes sequence, or a string if run() was called with universal_newlines=True. None if stdout was not captured.

If you ran the process with stderr=subprocess.STDOUT, stdout and stderr will be combined in this attribute, and stderr will be None.

 

subprocess.PIPE

Special value that can be used as the stdin, stdout or stderr argument to Popen and indicates that a pipe to the standard stream should be opened. Most useful with Popen.communicate().

 

在windows下使用python脚本运行cmd命令,运行原理会在当前进程下面产生子进程:

import  subprocess

print(u'测试开始')

subprocess.Popen('dir',shell=True)

subprocess.Popen('ping 192.168.1.1',shell=True)

print(u'测试结束')

以上代码输出如下:

C:\doc>python test.py
测试开始
测试结束
 驱动器 C 中的卷没有标签。
 卷的序列号是 0940-09B9

 C:\doc 的目录

2019/04/25  14:38    <DIR>          .
2019/04/25  14:38    <DIR>          ..
2019/04/18  12:08    <DIR>          deep learning
2019/04/24  13:11    <DIR>          forTest
2019/04/23  17:56    <DIR>          sphinx
2019/04/26  10:38               166 test.py
2019/04/25  11:11    <DIR>          __pycache__

C:\doc>               1 个文件            166 字节
               6 个目录 214,888,738,816 可用字节

正在 Ping 192.168.1.1 具有 32 字节的数据:
来自 192.168.1.1 的回复: 字节=32 时间<1ms TTL=64
来自 192.168.1.1 的回复: 字节=32 时间<1ms TTL=64
来自 192.168.1.1 的回复: 字节=32 时间<1ms TTL=64
来自 192.168.1.1 的回复: 字节=32 时间<1ms TTL=64

192.168.1.1 的 Ping 统计信息:
    数据包: 已发送 = 4,已接收 = 4,丢失 = 0 (0% 丢失),
往返行程的估计时间(以毫秒为单位):
    最短 = 0ms,最长 = 0ms,平均 = 0ms

C:\doc>

第一个参数subprocess.run是要执行的shell命令,默认应该是一个字符串序列,如['df', '-Th']或('df', '-Th'),也可以是一个字符串,如'df -Th',但是此时需要把shell参数的值置为True。

subprocess模块用于帮助我们在python代码中去执行一些系统命令,在执行python程序时,该模块会创建出一个子进程,来运行外部程序。


将lambda函数赋值给一个变量,通过这个变量间接调用该lambda函数。

    例如,执行语句add=lambda x, y: x+y,定义了加法函数lambda x, y: x+y,并将其赋值给变量add,这样变量add便成为具有加法功能的函数。例如,执行add(1,2),输出为3。
 

filter函数。此时lambda函数用于指定过滤列表元素的条件。例如filter(lambda x: x % 3 == 0, [1, 2, 3])指定将列表[1,2,3]中能够被3整除的元素过滤出来,其结果是[3]。

map函数。此时lambda函数用于指定对列表中每一个元素的共同操作。例如map(lambda x: x+1, [1, 2,3])将列表[1, 2, 3]中的元素分别加1,其结果[2, 3, 4]。 

 

map()

将序列中的元素通过处理函数处理后返回一个新的列表
filter()

将序列中的元素通过函数过滤后返回一个新的列表
reduce()

将序列中的元素通过一个二元函数处理返回一个结果
将上面三个函数和lambda结合使用

li = [1, 2, 3, 4, 5]
# 序列中的每个元素加1
map(lambda x: x+1, li) # [2,3,4,5,6]
 
# 返回序列中的偶数
filter(lambda x: x % 2 == 0, li) # [2, 4]
 
# 返回所有元素相乘的结果
reduce(lambda x, y: x * y, li) # 1*2*3*4*5 = 120

You can use **kwargs to let your functions take an arbitrary number of keyword arguments ("kwargs" means "keyword arguments"):

>>> def print_keyword_args(**kwargs):
...     # kwargs is a dict of the keyword args passed to the function
...     for key, value in kwargs.iteritems():
...         print "%s = %s" % (key, value)
... 
>>> print_keyword_args(first_name="John", last_name="Doe")
first_name = John
last_name = Doe

 

Python中单个下划线的作用

1. 在python的解释器状态中,表示刚才输出的内容

2. 下划线还可以当做毫无意义的占位符号

# 例子1:
for _ in range(10):     
    print('哈') 


# 例子2:
li=[('a',99),('b',100)]
for _,v in li:
    print(v)
# 解释:输出99和100。如果变成for v,_ in li:就会输出a和b。如果变成for v in li就会输出两个完整的元组('a',99)和('b',100)。


# 例子3:
a=(101,102,103,104,105)
x,_,z,_,_=a
print(x,z)
# 解释:输出101,103


# 例子4:
a=(101,102,103,104,105)
x,_,z,_,_=a
print(x,z)
# 解释:输出101,105

1、json.dumps()和json.loads()是json格式处理函数(可以这么理解,json是字符串)
  (1)json.dumps()函数是将一个Python数据类型列表进行json格式的编码(可以这么理解,json.dumps()函数是将字典转化为字符串)
  (2)json.loads()函数是将json格式数据转换为字典(可以这么理解,json.loads()函数是将字符串转化为字典)

2、json.dump()和json.load()主要用来读写json文件函数

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
SubprocessPython标准库中用于创建新进程的模块。它允许你启动一个新的进程,并与该进程进行交互,包括向其输入数据、从其输出数据等。 其中,communicate()方法是Subprocess模块中最常用的方法之一,它用于与子进程进行交互。当你使用Subprocess启动一个新的进程时,你可以在communicate()方法中向该进程输入数据,并在该进程完成后从该进程读取输出数据。 具体来说,communicate()方法会向进程的标准输入发送数据,并等待该进程完成后读取其标准输出和标准错误输出。该方法会返回一个元组,其中第一个元素表示标准输出,第二个元素表示标准错误输出。 例如,下面的代码展示了如何使用Subprocess模块来启动一个新的进程,并将数据传递给该进程: ``` import subprocess # 启动一个新的进程 process = subprocess.Popen(['python', 'my_script.py'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # 向进程发送数据 process.stdin.write('input data'.encode()) # 等待进程完成并读取其输出数据 output, error = process.communicate() # 打印输出结果 print(output.decode()) ``` 在上面的代码中,我们启动了一个新的进程,并将一个字符串作为输入数据发送给该进程。然后,我们使用communicate()方法等待该进程完成,并读取其标准输出和标准错误输出。最后,我们将输出结果打印出来。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值