python road day5

subprocess module

Foreshadowing:
1.
For the system in the os module of the os module, use os.system("dir") to directly output the result. If os.system("dir") is assigned to a variable, the variable receives the command to execute Whether it is successful or not, if it is not 0, the execution is unsuccessful, and 0 means the execution is successful.
a=os.popen("dir").read() will save the command output and assign it to a. At this time, print(a) can be output to the screen
. 2. Commands module: only used in linux

Correct topic:
subprocess.run(['df','-h'])
When the pipe character is involved, subprocess.run('df -h | grp sda1',shell=True)

subprocess.getstatusoutput('ls /bin/ls') receives a string format command and returns a tuple format, the first element is the execution status, and the second is the command result (0,'/bin/ls')

Other methods such as getoutput, check_output, check_call, etc. are not often used

For the above methods, the bottom layer is encapsulated subprocess.Popen
Example 1: res=subprocess.Popen("ifconfig |grep 192", shell=Ture, stdout=subprocess.PIPE) This is the pipeline that saves the command execution result in the memory space , if you want to output to the screen, you need to use res.stdout.read(). There is an error in the command input error. If an error is reported, the error will be directly input to the screen, and the pipeline is empty. If you want to save the error information, you need to increase the stderr=subprocess.PIPE field, and the error information is also saved in the pipeline at this time.
Example 2: poll() and wait() methods
in example 1 if the command execution takes a long time, such as: res=subprocess.Popen("sleep 10;echo 'hello'",shell=Ture,stdout=subprocess.PIPE ,stderr=subprocess.PIPE), when using res.stdout.read(), it will wait for the command execution to end before it can be displayed, and the poll method can detect whether the command execution ends, 0 indicates the execution end, and can be used in conjunction with read in programming, optimizer. The same wait method is to wait for the program to execute.
Example 3: terminate()
This method can interrupt execution, such as: res=subprocess.Popen("sleep 10;echo 'hello'",shell=Ture,stdout=subprocess.PIPE,stderr=subprocess.PIPE) It takes 10s to After the execution is completed, it can be output to the screen through res.stdout.read(). If res.terminate() is used in the middle, and the read method is called again, it will be empty.
Available parameters:

  • args: shell command, can be string or sequence type
  • cwd: used to set the current directory of the child process
  • stdin, stdout, stderr: respectively represent the standard input, output, and error handle of the program
  • env: Environment variables used to specify the child process. If env=None, the environment variables of the child process will be inherited from the parent process

object oriented

Concept
OOP (object oriented programming) programming is to use classes and objects to create various models to describe the real world. Object oriented programming can make program maintenance and expansion easier and improve development efficiency.
Core Features

  1. Class: An abstract collection of the same properties of a class.
  2. Object: The instantiated instance of a class, that is, the entity generated by the calling class.
  3. Encapsulation encapsulation: The assignment of data and internal calls in the class are transparent to external users, which turns the class into a capsule or container, which contains the data and methods of the class. The reason for encapsulation is to prevent data from being arbitrarily modified, and to make it convenient and quick to call external programs without paying attention to internal structures.
  4. Inheritance: A class can derive subclasses, and the properties and methods defined in this parent class are automatically inherited by the subclasses.
  5. Polymorphism: One interface, many implementations. It means that different subclasses are derived from a base class, and each subclass inherits the same method name and implements the methods of the parent class differently. This is the variety of the same thing.

class definition

class dog(object):
    def __init__(self,name,food): #构造函数
        self.NAME = name
        self.FOOD = food
    def sayhi(self):
        print("Hi,i am a dog,my name is %s" %self.NAME)

    def eat(self):
        print("I like eat %s" %self.FOOD)

d1 = dog('Sanmao','apple')
d2 = dog('lisi','banana')

print(d1.NAME)
d2.sayhi()
d1.eat()
d2.eat()

Inheritance
The inherited class is called the "base class"
Code example:

class Person(object):
    def talk(self):
        print("会说话")

class chinaperson(Person):
    def walk(self):
        print("会走路")
a = chinaperson()#实例a同时具有自己定义的属性walk和从基类中继承的属性talk
a.talk()
a.walk()

Specific applications: school examples

import time
class ShoolMember(object):
    member = 0
    def __init__(self,name,age,sex):#构造函数
        self.name = name
        self.age = age
        self.sex = sex
        self.enroll()

    def enroll(self):
        '''注册'''
        print('enroll a new member',self.name)
        ShoolMember.member += 1

    def tell(self):
        print('--------------info %s----------------'%self.name)
        for a,v in self.__dict__.items():
            print('\t',a,v)

    def __del__(self):#析构函数,在程序运行结束后自动执行,手动删除s2,运行结束后自动删除t1和s1
        print('开除了',self.name)
        ShoolMember.member -=1

class Teacher(ShoolMember):
    def __init__(self,name,age,sex,salary,course):#先继承,再重构
        ShoolMember.__init__(self,name,age,sex)  #经典类写法
        #super(Teacher,self).__init__(name,age,sex)新式类写法
        self.salary = salary
        self.course = course

    def teaching(self):
        print('%s is teaching %s'%(self.name,self.course))

class Student(ShoolMember):
    def __init__(self,name,age,sex,course,tuition):
        ShoolMember.__init__(self,name,age,sex)
        self.course = course
        self.tuition =tuition

    def study(self):
        print('%s is studing %s,course  is %s'%(self.name,self.course,self.tuition))

t1 = Teacher('zhangsan',30,'F',30000,'python')
s1 = Student('lisi',24,'M','python',11000)
s2 = Student('wangwu',18,'M','python',11000)
#print(s1.__dict__)使用该方法可以获取实例的所有参数,即可在tell函数中使用该方法
t1.tell()
s1.tell()
print('学校总人数',ShoolMember.member)
del s2
print('学校总人数',ShoolMember.member)
time.sleep(5)
# t1.teaching()
# s1.study()

classic and new

class A(object):
    def __init__(self):
        self.n = 'A'

class B(A):
    pass
    # def __init__(self):
    #     self.n = 'B'

class C(A):
    def __init__(self):
        self.n = 'C'

class D(B,C):
    pass
    # def __init__(self):
    #     self.n = 'D'
'''
D继承B、C,B、C继承A
正常情况下print(D().n)输出的是D
如果class D修改成pass,输出的是B
如果class B修改成pass,输出的是C
如果class C修改成pass,输出的是A
此查询方法称之为广度查询,即先查询同级的B、C,都查不到的情况下才查上级A
以上方法为新式类写法
如果把class A修改为经典类写法,其它保持不变,并在python2环境中运行(在python3环境中也遵循广度查询法)
class A:
    def __init__(self):
        self.n = 'A'
则遵循深度查询
'''
print(D().n)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326268130&siteId=291194637