学习lava源码时遇到的python知识

内置函数

参考:
https://docs.python.org/3.7/library/functions.html

Built-in Functions
abs()delattr()hash()memoryview()
all()dict()help()min()
any()dir()hex()next()
ascii()divmod()id()object()
bin()enumerate()input()oct()
bool()eval()int()open()
breakpoint()exec()isinstance()ord()
bytearray()filter()issubclass()pow()
bytes()float()iter()print()
callable()format()len()property()
chr()frozenset()list()range()
classmethod()getattr()locals()repr()
compile()globals()map()reversed()
complex()hasattr()max()round()

super ()

执行基类中的方法

isinstance()

Fixes duplicate types in the second argument of isinstance(). For example, isinstance(x, (int, int)) is converted to isinstance(x, int) and isinstance(x, (int, float, int)) is converted to isinstance(x, (int, float)).

file method

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
#Open file and return a corresponding file object. If the file cannot be opened, an OSError is raised.

decorator

A function returning another function, usually applied as a function transformation using the @wrapper syntax. Common examples for decorators are classmethod() and staticmethod().

The decorator syntax is merely syntactic sugar, the following two function definitions are semantically equivalent:

def f(...):
    ...
f = staticmethod(f)

@staticmethod
def f(...):
    ...

The same concept exists for classes, but is less commonly used there.

context manager

https://docs.python.org/3.7/library/stdtypes.html#typecontextmanager
https://docs.python.org/3.7/reference/datamodel.html#context-managers
https://docs.python.org/3.7/reference/compound_stmts.html#the-with-statement
A context manager is an object that defines the runtime context to be established when executing a with statement. The context manager handles the entry into, and the exit from, the desired runtime context for the execution of the block of code. Context managers are normally invoked using the with statement (described in section The with statement), but can also be used by directly invoking their methods.
例如:

with A() as a, B() as b:
    suite
#或者
with A() as a:
    with B() as b:
        suite

Sequence Types — list, tuple, range

https://docs.python.org/3.7/library/stdtypes.html?highlight=list#sequence-types-list-tuple-range

list

  • list.extend(seq)
    extend() 函数用于在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)。
  • list.append(obj)
    在列表末尾添加新的对象

endwith

  • str.endswith(suffix[, start[, end]])
    Return True if the string ends with the specified suffix, otherwise return False. suffix can also be a tuple of suffixes to look for. With optional start, test beginning at that position. With optional end, stop comparing at that position.
  • bytes.endswith(suffix[, start[, end]])
  • bytearray.endswith(suffix[, start[, end]])
    Return True if the binary data ends with the specified suffix, otherwise return False. suffix can also be a tuple of suffixes to look for. With optional start, test beginning at that position. With optional end, stop comparing at that position.

The suffix(es) to search for may be any bytes-like object.

模块

sys模块

System-specific parameters and functions.
This module provides access to some variables used or maintained by the interpreter and to functions that interact strongly with the interpreter. It is always available.

sys.argv

The list of command line arguments passed to a Python script. argv[0] is the script name (it is operating system dependent whether this is a full pathname or not). If the command was executed using the -c command line option to the interpreter, argv[0] is set to the string ‘-c’. If no script name was passed to the Python interpreter, argv[0] is the empty string.

To loop over the standard input, or the list of files given on the command line, see the fileinput module.

sys.path

A list of strings that specifies the search path for modules. Initialized from the environment variable PYTHONPATH, plus an installation-dependent default.

As initialized upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter. If the script directory is not available (e.g. if the interpreter is invoked interactively or if the script is read from standard input), path[0] is the empty string, which directs Python to search modules in the current directory first. Notice that the script directory is inserted before the entries inserted as a result of PYTHONPATH.

A program is free to modify this list for its own purposes. Only strings and bytes should be added to sys.path; all other data types are ignored during import.

argparse模块

参考:
https://docs.python.org/3.7/library/argparse.html
https://docs.python.org/2/library/argparse.html

用来方便地处理程序参数.

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)

Create a new ArgumentParser object. All parameters should be passed as keyword arguments.

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

Define how a single command-line argument should be parsed.

ArgumentParser.parse_args(args=None, namespace=None)

Convert argument strings to objects and assign them as attributes of the namespace. Return the populated namespace.

Previous calls to add_argument() determine exactly what objects are created and how they are assigned. See the documentation for add_argument() for details.

  • args - List of strings to parse. The default is taken from sys.argv.
  • namespace - An object to take the attributes. The default is a new empty Namespace object.
ArgumentParser.add_subparsers([title][, description][, prog][, parser_class][, action][, option_string][, dest][, required][, help][, metavar])

Many programs split up their functionality into a number of sub-commands, for example, the svn program can invoke sub-commands like svn checkout, svn update, and svn commit. Splitting up functionality this way can be a particularly good idea when a program performs several different functions which require different kinds of command-line arguments. ArgumentParser supports the creation of such sub-commands with the add_subparsers() method. The add_subparsers() method is normally called with no arguments and returns a special action object. This object has a single method, add_parser(), which takes a command name and any ArgumentParser constructor arguments, and returns an ArgumentParser object that can be modified as usual.

ArgumentParser.add_argument_group(title=None, description=None)

By default, ArgumentParser groups command-line arguments into “positional arguments” and “optional arguments” when displaying help messages. When there is a better conceptual grouping of arguments than this default one, appropriate groups can be created using the add_argument_group() method.

例子:

# Creating a parser
parser = argparse.ArgumentParser(description='Process some integers.')

# Adding arguments
parser.add_argument('integers', metavar='N', type=int, nargs='+',
                    help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
                    const=sum, default=max,
                    help='sum the integers (default: find the max)')

# Parsing arguments
args = parser.parse_args()

# Use the args
print args.accumulate(args.integers)

glob模块

https://docs.python.org/3.7/library/glob.html
Unix style pathname pattern expansion

glob.glob(pathname, *, recursive=False)
#返回跟pathname指定的路径相匹配的所有路径列表,结果可能为空.
#pathname可以是绝对路径,也可以是相对路径,还可以包括shell通配符,但是不支持~ 和shell变量展开.

glob.iglob(pathname, *, recursive=False)
#Return an iterator which yields the same values as glob() without actually storing them all simultaneously.

glob.escape(pathname)
#Escape all special characters ('?', '*' and '['). This is useful if you want to match an arbitrary literal string that may have special characters in it. 

os.path 模块

https://docs.python.org/3.7/library/os.path.html
Common pathname manipulations

os.path.join(path, *paths)
#Join one or more path components intelligently. 

os.path.realpath(path)
#Return the canonical path of the specified filename, eliminating any symbolic links encountered in the path (if they are supported by the operating system).

os.path.relpath(path, start=os.curdir)
#Return a relative filepath to path either from the current directory or from an optional start directory.

pkg_resources模块

https://setuptools.readthedocs.io/en/latest/pkg_resources.html

ConfigParser模块

https://docs.python.org/3.7/library/configparser.html?highlight=configparser#module-configparser

requests模块

requests是一个优雅简洁的HTTP python库.
http://docs.python-requests.org/en/master/user/quickstart/#make-a-request
http://docs.python-requests.org/en/master/user/quickstart/
例子:

import requests
r = requests.get('https://api.github.com/events')
r = requests.post('https://httpbin.org/post', data = {'key':'value'})
r = requests.put('https://httpbin.org/put', data = {'key':'value'})
r = requests.delete('https://httpbin.org/delete')
r = requests.head('https://httpbin.org/get')
r = requests.options('https://httpbin.org/get')

xmlrpclib模块

参考: https://docs.python.org/2/library/xmlrpclib.html
xmlrpclib
一般使用在客户端,这个模块用来调用注册在XML-RPC服务器端的函数,xmlrpclib并不是一个类型安全的模块,无法抵御恶意构造的数据,这方面的一些处理工作需要交给开发者自己。

SimpleXMLRPCServer
一般使用在服务器端,这个模块用来构造一个最基本的XML-RPC服务器框架。

大致用法:使用SimpleXMLRPCServer模块运行XMLRPC服务器,在其中注册服务器提供的函数或者对象;然后在客户端内使用xmlrpclib.ServerProxy连接到服务器,想要调用服务器的函数,直接调用ServerProxy即可。

hashlib模块

https://docs.python.org/3.7/library/hashlib.html
hashlib主要提供字符加密功能,将md5和sha模块整合到了一起,支持md5,sha1, sha224, sha256, sha384, sha512等算法.

tmpefile模块

https://docs.python.org/3.7/library/tempfile.html?highlight=tempfile#module-tempfile
这个模块用于产生临时文件和目录. 它可以在所有平台上工作. TemporaryFile, NamedTemporaryFile, TemporaryDirectory 和 SpooledTemporaryFile是高级接口, 会自动进行清理工作,而mkstemp() 和 mkdtemp() 是低级接口, 需要手动清理.

#创建临时文件, 一旦文件被关闭,这个文件也会被删除, 在Unix系统中,它的directory entry要么根本不会创建,要么创建完之后会被立马删除
tempfile.TemporaryFile(mode='w+b', buffering=None, encoding=None, newline=None, suffix=None, prefix=None, dir=None)

#与TemporaryFile()类似,但是能保证文件在系统上有一个显示的名字(Unix上,该目录entry不会被unlinked掉).文件名字可以从返回的类似文件的对象的属性检索到.
tempfile.NamedTemporaryFile(mode='w+b', buffering=None, encoding=None, newline=None, suffix=None, prefix=None, dir=None, delete=True)

#类似TemporaryFile(),但是它的数据会在内存中spooled(卷,缠绕?)直到文件大小达到max_size,或者直到文件的fileno()方法被调用(数据被写入磁盘或数据处理等等).
tempfile.SpooledTemporaryFile(max_size=0, mode='w+b', buffering=None, encoding=None, newline=None, suffix=None, prefix=None, dir=None)

#创建临时目录,返回的对象可以作为一个context manager, 可以使用with
tempfile.TemporaryDirectory(suffix=None, prefix=None, dir=None)

#创建临时文件
tempfile.mkstemp(suffix=None, prefix=None, dir=None, text=False)

#创建临时目录
tempfile.mkdtemp(suffix=None, prefix=None, dir=None) 

tempfile.gettempdir()
tempfile.gettempdirb()
tempfile.gettempprefix()
tempfile.gettempprefixb()
tempfile.tempdir

tarfile

https://docs.python.org/3.7/library/tarfile.html
读写压缩包文件
tarfile包可以用来读写用gzip, bz2 和 lzma 方法压缩的文件. 可以用zipfile模块读写.zip文件.

class tarfile.TarFile
Class for reading and writing tar archives. **
Do not use this class directly: use tarfile.open() instead.**

#打开name指定的文件,返回一个TarFile对象
tarfile.open(name=None, mode='r', fileobj=None, bufsize=10240, **kwargs)

#如果是tar文件,返回True
tarfile.is_tarfile(name)

#为name指定的tar包成员返回一个TarInfo对象
TarFile.getmember(name)

#Return the members of the archive as a list of TarInfo objects. The list has the same order as the members in the archive.
TarFile.getmembers()

#Return the members as a list of their names. It has the same order as the list returned by getmembers().
TarFile.getnames()

TarFile.extractall(path=".", members=None, *, numeric_owner=False)

TarFile.extract(member, path="", set_attrs=True, *, numeric_owner=False)

TarFile.extractfile(member)

#将name指定的文件添加到tar包中,如果recursive为True, 则递归地将name中的内容添加到tar包中
TarFile.add(name, arcname=None, recursive=True, *, filter=None)

TarFile.addfile(tarinfo, fileobj=None)

#从os.stat()结果返回一个 TarInfo 对象
TarFile.gettarinfo(name=None, arcname=None, fileobj=None)

TarFile.close()

subprocess

https://docs.python.org/3.7/library/subprocess.html
subprocess是子进程管理模块.
The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. This module intends to replace several older modules and functions:
os.system
os.spawn

#Run the command described by args. Wait for command to complete, then return a CompletedProcess instance.
# class subprocess.CompletedProcess
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)

#Execute a child program in a new process.
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, text=None)


Popen.poll()
##Check if child process has terminated. Set and return returncode attribute. Otherwise, returns None.

Popen.wait(timeout=None)
#Wait for child process to terminate. Set and return returncode attribute.

Popen.communicate(input=None, timeout=None)
#Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. 
#communicate() returns a tuple (stdout_data, stderr_data). 

Popen.send_signal(signal)
#Sends the signal signal to the child.

Popen.terminate()
#Stop the child. On Posix OSs the method sends SIGTERM to the child. On Windows the Win32 API function TerminateProcess() is called to stop the child.

Popen.kill()
#Kills the child. On Posix OSs the function sends SIGKILL to the child. On Windows kill() is an alias for terminate().
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值