python tricks

本文介绍了Python中super()函数在类继承中的应用技巧,包括单继承、多重继承等情况下的使用方法,以及如何避免多次调用基类构造函数。此外,还详细讲解了subprocess模块的常见用法,如call、check_call、check_output和Popen方法,帮助读者掌握子进程的管理和交互。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、Python类中super()和__init__()的关系

转载:开源中国

1. 单继承时super()和__init__()实现的功能是类似的
class Base(object):
    def __init__(self):
        print 'Base create'
 
class childA(Base):
    def __init__(self):
        print 'creat A ',
        Base.__init__(self)

class childB(Base):
    def __init__(self):
        print 'creat B ',
        super(childB, self).__init__()
 
base = Base()
a = childA()
b = childB()

#输出:

Base create
creat A  Base create
creat B  Base create

使用super()继承时不用显式引用基类。

2. super()只能用于新式类中。

把基类改为旧式类,即不继承任何基类

class Base():
    def __init__(self):
        print 'Base create'

#执行时,在初始化b时就会报错

super(childB, self).__init__()
TypeError: must be type, not classobj
3. super不是父类,而是继承顺序的下一个类

在多重继承时会涉及继承顺序,super()相当于返回继承顺序的下一个类,而不是父类,类似于这样的功能:

def super(class_name, self):
    mro = self.__class__.mro()
    return mro[mro.index(class_name) + 1]

#mro()用来获得类的继承顺序。

例如:

class Base(object):
    def __init__(self):
        print 'Base create'
 
class childA(Base):
    def __init__(self):
        print 'enter A '
        # Base.__init__(self)
        super(childA, self).__init__()
        print 'leave A'
 
class childB(Base):
    def __init__(self):
        print 'enter B '
        # Base.__init__(self)
        super(childB, self).__init__()
        print 'leave B'
 
class childC(childA, childB):
    pass
 
c = childC()
print c.__class__.__mro__

#输出:

enter A 
enter B 
Base create
leave B
leave A
(<class '__main__.childC'>, <class '__main__.childA'>, <class '__main__.childB'>, <class '__main__.Base'>, <type 'object'>)
4. super() 避免多次调用

如果childA基础Base, childB继承childA和Base,如果childB需要调用Base的__init__()方法时,就会导致__init__()被执行两次:

class Base(object):
    def __init__(self):
        print 'Base create'
 
class childA(Base):
    def __init__(self):
        print 'enter A '
        Base.__init__(self)
        print 'leave A'
 
class childB(childA, Base):
    def __init__(self):
        childA.__init__(self)
        Base.__init__(self)
 
b = childB()

#Base的__init__()方法被执行了两次
#输出:

enter A 
Base create
leave A
Base create

使用super()避免多次调用,如下:

class Base(object):
    def __init__(self):
        print 'Base create'
 
class childA(Base):
    def __init__(self):
        print 'enter A '
        super(childA, self).__init__()
        print 'leave A'
 
 
class childB(childA, Base):
    def __init__(self):
        super(childB, self).__init__()
 
b = childB()
print b.__class__.mro()

#输出:

enter A 
Base create
leave A
[<class '__main__.childB'>, <class '__main__.childA'>, <class '__main__.Base'>, <type 'object'>]

二、python的subprocess模块

转载:python的subprocess模块
subprocess模块是python从2.4版本开始引入的模块。主要用来取代 一些旧的模块方法,如os.system、os.spawn*、os.popen*、commands.*等。subprocess通过子进程来执行外部指令,并通过input/output/error管道,获取子进程的执行的返回信息。

常用方法:

1. subprocess.call():

执行命令,并返回执行状态,其中shell参数为False时,命令需要通过列表的方式传入,当shell为True时,可直接传入命令

示例如下:

>>> a = subprocess.call(['df','-hT'],shell=False)
Filesystem    Type    Size  Used Avail Use% Mounted on
/dev/sda2     ext4     94G   64G   26G  72% /
tmpfs        tmpfs    2.8G     0  2.8G   0% /dev/shm
/dev/sda1     ext4    976M   56M  853M   7% /boot

>>> a = subprocess.call('df -hT',shell=True)
Filesystem    Type    Size  Used Avail Use% Mounted on
/dev/sda2     ext4     94G   64G   26G  72% /
tmpfs        tmpfs    2.8G     0  2.8G   0% /dev/shm
/dev/sda1     ext4    976M   56M  853M   7% /boot

>>> print a
0

当使用shell=False的时候,我们常使用python shlex 模块,shkex 模块最常见的用法就是其中的split 函数,split 函数提供了和shell 处理命令行参数时一致的分隔方式。在shell 中,对于选项和对应的值之间可以有多个空格,而shlex.split 保持了和sell 一致的处理方式。
示例:

cmd = 'git log -n 1 --pretty="%h" '
return = subprocess.check_output(shlex.split(cmd)).strip()
2. subprocess.check_call():

用法与subprocess.call()类似,区别是,当返回值不为0时,直接抛出异常

示例:

>>> a = subprocess.check_call('df -hT',shell=True)
Filesystem    Type    Size  Used Avail Use% Mounted on
/dev/sda2     ext4     94G   64G   26G  72% /
tmpfs        tmpfs    2.8G     0  2.8G   0% /dev/shm
/dev/sda1     ext4    976M   56M  853M   7% /boot
>>> print a
0

>>> a = subprocess.check_call('dfdsf',shell=True)
/bin/sh: dfdsf: command not found
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python2.6/subprocess.py", line 502, in check_call
    raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command 'dfdsf' returned non-zero exit status 127
3. subprocess.check_output():

用法与上面两个方法类似,区别是,如果当返回值为0时,直接返回输出结果,如果返回值不为0,直接抛出异常。需要说明的是,该方法在python3.x中才有。

4. subprocess.Popen():

在一些复杂场景中,我们需要将一个进程的执行输出作为另一个进程的输入。在另一些场景中,我们需要先进入到某个输入环境,然后再执行一系列的指令等。这个时候我们就需要使用到suprocess的Popen()方法。该方法有以下参数:

  • args:shell命令,可以是字符串,或者序列类型,如list,tuple。
  • bufsize:缓冲区大小,可不用关心
  • stdin,stdout,stderr:分别表示程序的标准输入,标准输出及标准错误
  • shell:与上面方法中用法相同
  • cwd:用于设置子进程的当前目录
  • env:用于指定子进程的环境变量。如果env=None,则默认从父进程继承环境变量
  • universal_newlines:不同系统的的换行符不同,当该参数设定为true时,则表示使用\n作为换行符

示例1,在/root下创建一个suprocesstest的目录:

>>> a = subprocess.Popen('mkdir subprocesstest',shell=True,cwd='/root')

示例2,使用python执行几个命令:

import subprocess

obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
obj.stdin.write('print 1 \n')
obj.stdin.write('print 2 \n')
obj.stdin.write('print 3 \n')
obj.stdin.write('print 4 \n')
obj.stdin.close()

cmd_out = obj.stdout.read()
obj.stdout.close()
cmd_error = obj.stderr.read()
obj.stderr.close()

print cmd_out
print cmd_error

也可以使用如下方法:

import subprocess

obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
obj.stdin.write('print 1 \n')
obj.stdin.write('print 2 \n')
obj.stdin.write('print 3 \n')
obj.stdin.write('print 4 \n')

out_error_list = obj.communicate()
print out_error_list

示例3,将一个子进程的输出,作为另一个子进程的输入:

import subprocess
child1 = subprocess.Popen(["cat","/etc/passwd"], stdout=subprocess.PIPE)
child2 = subprocess.Popen(["grep","0:0"],stdin=child1.stdout, stdout=subprocess.PIPE)
out = child2.communicate()

其他方法:

import subprocess
child = subprocess.Popen('sleep 60',shell=True,stdout=subprocess.PIPE)
child.poll()    #检查子进程状态
child.kill()     #终止子进程
child.send_signal()    #向子进程发送信号
child.terminate()   #终止子进程
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值