Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the Python classes?

2025-04-03 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the relevant knowledge of "what are the Python classes?". In the operation of actual cases, many people will encounter such a dilemma. Then let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Shutil:

Shutil.copyfile (src, dst) # is copied from the source src to dst. If the current dst already exists, it will be overwritten

Shutil.move (src, dst) # move files or rename

Shutil.copymode (src, dst) # will only copy its permissions and nothing else will be copied.

Shutil.copystat (src, dst) # copy permission, last access time, last modification time

Shutil.copy (src, dst) # copy a file to a file or a directory

Shutil.copy2 (src, dst) # copy the file on the basis of copy the last access time and modification time are also copied, something similar to cp-p

Shutil.copy2 (src, dst) # if the file system of the two locations is the same, it is equivalent to a rename operation, just renaming; if it is not on the same file system, it is a move operation.

Shutil.copytree (olddir, newdir, True/Flase) # copy the olddir into a newdir. If the third parameter is True, the symbolic connection under the folder will be maintained when copying the directory. If the third parameter is False, a physical copy will be generated under the copied directory instead of the symbolic link.

Shutil.rmtree (src) # Recursively delete a directory and all the contents in the directory

Subprocess

The subprocess module allows us to start a new process and connect to their input / output / error pipes to get the return value.

Use the subprocess module

The first thing the subprocess module recommends is its run method, and for more advanced uses, you can use the Popen interface directly.

The syntax format of the run method is as follows:

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

Args: represents the command to be executed. Must be a string, a list of string parameters.

Stdin, stdout, and stderr: standard input, output, and errors for child processes. Its value can be subprocess.PIPE, subprocess.DEVNULL, an existing file descriptor, an open file object, or None. Subprocess.PIPE means to create a new pipe for the child process. Subprocess.DEVNULL means to use os.devnull. None is used by default, which means to do nothing. In addition, stderr can be merged into stdout and output together.

Timeout: sets the command timeout. If the command time expires, the child process is killed and a TimeoutExpired exception pops up.

Check: if this parameter is set to True and the process exit status code is not 0, a CalledProcessError exception pops up.

Encoding: if this parameter is specified, stdin, stdout, and stderr can receive string data and encode it in this encoding. Otherwise, only data of type bytes is received.

Shell: if this parameter is True, the specified command will be executed through the operating system's shell.

The run method call returns the CompletedProcess instance, which is similar to the direct Popen, and the implementation is the same. It actually calls Popen, which is roughly the same as the Popen constructor, for example:

Example

# execute ls-l / dev/null command

> subprocess.run (["ls", "- l", "/ dev/null"])

Crw-rw-rw- 1 root wheel 3, 2 5 4 13:34 / dev/null

CompletedProcess (args= ['ls','-lumped,'/ dev/null'], returncode=0)

Returncode: execution of the child process status. Usually a return status of 0 indicates that it has finished running. If the value is negative "- N", it indicates that the child process is terminated.

Simple example:

Example

Import subprocess

Def runcmd (command):

Ret = subprocess.run (command,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE,encoding= "utf-8", timeout=1)

If ret.returncode = = 0:

Print ("success:", ret)

Else:

Print ("error:", ret)

Runcmd (["dir", "/ b"]) # sequence parameters

Runcmd ("exit 1") # string parameter

The output is as follows:

Success: CompletedProcess (args= ['dir',' / b'], returncode=0, stdout='test.py\ nkeeper, stderr='')

Error: CompletedProcess (args='exit 1, returncode=1, stdout='', stderr='')

Popen () method

Popen is the core of subprocess, and it handles the creation and management of child processes.

Constructor:

Class subprocess.Popen (args, bufsize=-1, executable=None, stdin=None, stdout=None, stderr=None

Preexec_fn=None, close_fds=True, shell=False, cwd=None, env=None, universal_newlines=False

Startupinfo=None, creationflags=0,restore_signals=True, start_new_session=False, pass_fds= ()

*, encoding=None, errors=None)

Common parameters:

Args:shell command, which can be a string or sequence type (e.g. list, tuple)

Bufsize: buffer size. Used when creating pipe objects for standard streams, the default is-1.

0: do not use buffer

1: indicates line buffering, available only when universal_newlines=True, that is, text mode

Positive number: indicates buffer size

Negative number: indicates that the system default buffer size is used.

Stdin, stdout, stderr: standard input, output, error handle of the program, respectively

Preexec_fn: valid only on Unix platforms and used to specify an executable object (callable object) that will be called before the child process runs

Shell: if this parameter is True, the specified command will be executed through the operating system's shell.

Cwd: used to set the current directory of the child process.

Env: the environment variable used to specify the child process. If env = None, the environment variables of the child process are inherited from the parent process.

Create a child process and execute a simple command:

Example

> import subprocess

> p = subprocess.Popen ('ls-lumped, shell=True)

> total 164,

-rw-r--r-- 1 root root 133 Jul 4 16:25 admin-openrc.sh

-rw-r--r-- 1 root root 268 Jul 10 15:55 admin-openrc-v3.sh

...

> p.returncode

> > p.wait ()

0

> p.returncode

You can also use p = subprocess.Popen (['ls','-cl']) to create child processes here.

Popen object method

Poll (): check whether the process is terminated, and return returncode if terminated, otherwise return None.

Wait (timeout): wait for the child process to terminate.

Communicate (input,timeout): interacts with child processes to send and read data.

Send_signal (singnal): sends a signal to a child process.

Terminate (): stops the child process, that is, sends a SIGTERM signal to the child process.

Kill (): kill the child process. Send a SIGKILL signal to the child process.

Example

Import time

Import subprocess

Def cmd (command):

Subp = subprocess.Popen (command,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE,encoding= "utf-8")

Subp.wait (2)

If subp.poll () = = 0:

Print (subp.communicate () [1])

Else:

Print (failure)

Cmd ("java-version")

Cmd ("exit 1")

The output is as follows:

Java version "1.8.031"

Java (TM) SE Runtime Environment (build 1.8.0_31-b13)

Java HotSpot (TM) 64-Bit Server VM (build 25.31-b07, mixed mode)

Fail

Signal module signal

Although signal is a module in Python, it is mainly aimed at the UNIX platform. Because the signaling mechanism is not fully supported in the Windows kernel, Python on Windows can not transmit the function of the signaling system.

The signal module of Python is responsible for signal processing within the program. Typical operations include signal processing functions, pausing and waiting for signals, and regularly sending out SIGALRM.

Load module

Import signal

Signal name

# connection hang up

Signal.SIGUP

# illegal instruction

Signal.SIGILL

# terminate the process

Signal.SIGINT

The SIGINT signal is numbered 2, which is received by the process when the keyboard CTRL+c key is pressed to terminate the process.

# pause process CTRL+z

Signal.SIGSTP

# Kill the process, this signal cannot be captured or ignored.

Signal.SIGKILL

SIGKILL signal is used to forcibly kill the process, this signal process can not be ignored, directly kill the process at the system level, so it can not be listened to in Python.

# Terminal exit

Signal.SIGQUIT

# termination signal, software termination signal.

Signal.SIGTERM

When the end user inputs kill sigerm pid, the process corresponding to PID will receive this signal, and the signal process can capture and specify function processing. For example, do some program cleaning and other work, of course, you can also ignore this signal.

# alarm clock signal, initiated by signal.alarm ().

Signal.SIGALRM

# continue with the pause process

Signal.SIGCONT

Signal processing function

Set the timer for sending SIGALRM signals

Signal.alarm (time)

Function: send SIGALRM signal to the process itself after time seconds

Parameter: time is a time parameter in seconds.

For example: set the clock

$vim sigalrm.py

#! / usr/bin/env python

#-*-coding:utf-8-*-

Import signal, time

# terminate the program after 3 seconds

Signal.alarm (3)

While True:

Time.sleep (1)

Print ("working")

$python sigalrm.py

Working

Working

Alarm clock

Only one clock can be set in a process. Setting the second will overwrite the time of the first and return the remaining time of the first, while the first alarm clock returns 0.

For example, when two signal.alarm () functions appear in a program

$vim sigalrm.py

#! / usr/bin/env python

#-*-coding:utf-8-*-

Import signal, time

# terminate the program after 3 seconds

Print (signal.alarm (3)) # output:0

Time.sleep (1)

Print (signal.alarm (3)) # output:2

While True:

Time.sleep (1)

Print ("working")

$python sigalrm.py

0

two

Working

Working

Alarm clock

Use the signal.pause blocking function to pause the process to wait for the signal, which blocks the process from executing, simply stopping the process when the signal is received.

For example:

$vim sigalrm.py

#! / usr/bin/env python

#-*-coding:utf-8-*-

Import signal, time

# terminate the program after 3 seconds

Print (signal.alarm (3)) # output:0

Time.sleep (1)

Print (signal.alarm (3)) # output:2

# blocking and waiting for the signal to occur, no matter what the signal is.

Signal.pause ()

While True:

Time.sleep (1)

Print ("working")

$python sigalrm.py

0

two

Alarm clock

Put the program into hibernation

Signal.pause ()

Function: put the program into hibernation until the program receives a semaphore

Gets the handler of the signalnum semaphore registered by the current program

Signal.getsignal (signalnum)

Function: get the handler of the signalnum semaphore registered by the current program

Return value: may make Python callable objects such as signal.SIG_DFL, signal.SIG_IGN, None.

Set signal processing function

Signal.signal (sig, handler)

Function: processing function according to the signal processing scheme established by handler processor

Parameters:

Sig is intended to process the signal, and the processing signal only aims at this kind of signal.

Handler signal processing scheme, the process can ignore the signal to take the default action can also be customized.

When handler is the following function, you will do the following

SIG_IGN signal is ignored ignore or ignored

The SIG_DFL process is handled with the default default behavior

When the function processor handler is used as the function name, the process uses a custom function.

SIGSTOP SIGKILL cannot handle but can only use

For example:

$vim signal.py

#! / usr/bin/env python

#-*-coding:utf-8-*-

Import signal, time

# terminate the program after 3 seconds

Signal.alarm (3)

# ignore SIG_IGN when you encounter SIGINT that is CTRL+C

Signal.signal (signal.SIGINT, signal.SIG_IGN)

# blocking and waiting for the signal to occur, no matter what the signal is.

Signal.pause ()

$python signal.py

Alarm clock

Signal interception

Why do you need to set up signal interception? If you use multithreading or multi-coprogramming, in order to prevent the main thread from ending while the subthreads and subcoroutines are still running, you need to use the signal module. Using the signal module, you can bind a handler function, and the program will not end immediately when the step signal is received.

There are usually two ways to intercept signals in Python

The first is to send out kill signals.

# SIGTERM indicates to turn off the program signal

Signal.signal (signal.SIGTERM, self._term_handler)

The second is to send out CTRL+C signals.

# SIGINT indicates CTRL+C signal

Signal.signal (signal.SIGINT, self._term_handler)

In the programming of multithreading and multi-programming, the general multithreaded or multi-programming program should design a program termination mark, and when the termination signal is received, the state of the termination tag should be changed from False to True. At this time, the program running can only be run when the termination mark is in False state. If the program needs to sleep, a sleep flag should also be added to the program. When the program is dormant, the sleep flag is set to True. When the termination signal is received, not only the termination flag is set to True, but also the sleep program is terminated.

Argparse:

Argparse is a standard module used by python to parse command-line parameters and options, similar to the ls instruction in linux, followed by different parameter options to achieve different functions, argparse can parse the command line and perform the corresponding operations.

Argparse usage

When using argparse to configure command line parameters, there are three steps:

Create an ArgumentParser () object

Call the add_argument () method to add parameters

Parse the added parameters using parse_args ()

Copy the code

Parser = argparse.ArgumentParser ()

Parser.add_argument ("- p", "--port"

Dest='port'

Default= "/ dev/ttyUSB0"

Help= "serial port where the MCU is connected to.)

Parser.add_argument ("- v", "--version"

Dest='version'

Action='store_true'

Help= "show the version number of this program and exit.")

Args = parser.parse_args ()

Copy the code

In some cases, you want to conceptually group parameters by function for ease of use, such as parameters for write operations as a group, parameters for read operations as a group, and you can use ArgumentParser.add_argument_group (title=None, description=None) to define a group.

1 info_group = parser.add_argument_group ('Device information')

2 read_group = parser.add_argument_group ('Read and compare functions')

3 write_group = parser.add_argument_group ('Erase and write functions')

4 run_group = parser.add_argument_group ('Code execution functions')

Method parameter lookup table

1.ArgumentParser class

Class argparse.ArgumentParser (prog=None, usage=None, description=None, epilog=None, parents= [], formatter_class=argparse.HelpFormatter, prefix_chars='-', fromfile_prefix_chars=None, argument_default=None, conflict_handler='error', add_help=True, allow_abbrev=True)

Parameters:

Prog: the name of the program

Usage: by default, ArgumentParser calculates help information based on the parameters it contains

Description: this parameter gives a brief description of what the program does and how it works

Epilog: displays additional descriptions of the program

Parents: sometimes several parsers share a common set of parameters. You can use a parser with all shared parameters to pass parents= parameters to ArgumentParser without having to define them repeatedly

The formatter_class:ArgumentParser object allows you to customize the format of help information (argparse.RawDescriptionHelpFormatter, argparse.RawTextHelpFormatter, argparse.ArgumentDefaultsHelpFormatter, argparse.MetavarTypeHelpFormatter) by specifying a formatting class.

Prefix_chars: modify prefix character

Fromfile_prefix_chars: parameters that start with any given character will be treated as files and will be replaced by the parameters contained in these files

Argument_default: specify a parser-wide parameter default value

Allow_abbrev: allow abbreviations (default)

Conflict_handler: have two actions about setting the same option

Add_help

2.ArgumentParser object add_argument () method

ArgumentParser.add_argument (name or flags... [, action] [, nargs] [, const] [, default] [, type] [, choices] [, required] [, help] [, metavar] [, dest])

Parameters.

Name or flags: the first parameter passed to add_argument () must therefore be a tag sequence or a simple parameter name

Action: indicates how command line arguments should be handled (supported operations: 'store',' store_const','store_true','store_false','append','append_const','count','help','version')

Nargs: associate an action with a different number of command line arguments. (supported values: NMagne.m.n.m.j.m.n.n.m.m.j.m.j.m.r.m.m.r.m.m.r..m..m.r..net.

Const: used to hold constant values that are not read from the command line but are required by the action of ArgumentParser

Default: its default value is None, which indicates what the command line arguments should be if they are not present

Type: allow any necessary type checking and type conversion

Choices: some command line arguments should be selected from a restricted collection

Required: if you want the option to be required, you can specify True as the value of the required= keyword parameter to add_argument ()

Help: a string containing a short description of the parameter

Metavar: by default, the value of dest is used directly for positional parameters, and the value of dest is capitalized for optional parameters. Note that metavar will only change the name displayed. The name of the property in the parse_args () object is still determined by the value of dest.

Dest: for actions with positional parameters, dest is usually provided to add_argument () as the first parameter, and for actions with optional parameters, dest actions are usually derived from the option string, for example, the value of dest generated by ArgumentParser removes the-string before the first long option string. If no long option string is provided, the dest is obtained by removing the-character before the first short option string. Any internal-will be converted to characters to ensure that the string is a valid attribute name. (that is, for optional parameters, find the long option string first, then the short option string, and the internal-is converted to characters. )

Action class

Class argparse.Action (option_strings, dest, nargs=None, const=None, default=None, type=None, choices=None, required=False, help=None, metavar=None)

3.ArgumentParser object parse_args () method

Converts a parameter numeric string to an object and sets it to a property of the namespace. Returns the constituent namespace.

The previous call to add_argument () completely determines what object is created and how it is set.

Option value syntax, the parse_args () method supports several ways to specify the value of an option:

The easiest way is to pass the option and its value as two separate parameters

For long options (options with names longer than one character), the option and its value can also be passed with a single command line argument, separated by =

For short options (options that are only one character long), options and their values can be concatenated

Several short options can be concatenated with only one-prefix, as long as only the last option requires a value or none

Invalid parameter

While parsing the command line, parse_args () checks for a variety of errors, including ambiguous options, illegal types, illegal options, the number of incorrect positional arguments, and so on. When it encounters such an error, it exits and prints the error along with the usage information.

The parameter contains "-"

The parse_args () method tries to give an error message whenever a user makes a specific error, but some cases are inherently ambiguous. For example, the command line argument-1 can either specify an option or provide a location parameter. Here parse_args () will be very careful: positional parameters can only start with-if they look negative and there is no option in the parser to look negative.

If you have positional parameters that must start with-and are not negative, you can insert the pseudo parameter'-'to tell parse_args () that everything after it is positional.

Parameter abbreviation (prefix match)

Parameter does not come from sys.argv

Sometimes the parameters that need to be parsed by ArgumentParser are not from sys.argv. This can be done by passing a list of strings to parse_args ()

4.class argparse.Namespace

A simple class used by parse_args () by default to create an object that holds properties and returns it.

Sometimes it may be necessary to have ArgumentParser assign properties to an existing object instead of a new Namespace object. This can be achieved by specifying the namespace= keyword parameter.

This is the end of the content of "what are the Python classes"? thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report