标准库sys

sys模块的主要函数介绍,结合官方文档说明和实例。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            命令行参数List,第一个元素是程序本身路径
sys.exit(n)        退出程序,正常退出时exit(0)
sys.version        获取Python解释程序的版本信息
sys.path            返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
sys.maxsize        返回最大值
sys.platform        返回操作系统平台名称
sys.stdout.write('please:')  
val = sys.stdin.readline()[:-1]  

sys 模块提供了许多函数和变量来处理 Python 运行时环境的不同部分.

处理命令行参数 sys.argv

sys模块包含系统对应的功能。我们已经学习了sys.argv列表,它包含命令行参数。

在解释器启动后, argv 列表包含了传递给脚本的所有参数, 列表的第一个元素为脚本自身的名称.

 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.

 

import sys
print('--->',sys.argv)
print('sys.argv[0]',sys.argv[0])
print('sys.argv[1:]',sys.argv[1:])

  在cmd中运行该脚本,在脚本os_func.py 后面输入 1 2 3,这些会传入sys.argv列表中。 

使用sys.argv的实例(转载改版为Python3.x):

 1 import sys
 2 def readfile(filename):  #定义readfile函数,从文件中读出文件内容
 3     '''''''''Print a file to the standard output.'''
 4     f = open('test.txt')
 5     while True:
 6         line = f.readline()
 7         if len(line) == 0:
 8             break
 9         print(line,)# notice comma  分别输出每行内容
10 
11     f.close()
12 # Script starts from here
13 print(sys.argv)
14 if len(sys.argv) < 2:
15     print('No action specified.')
16     sys.exit()
17 if sys.argv[1].startswith('--'):
18     option = sys.argv[1][2:]
19     # fetch sys.argv[1] but without the first two characters
20     if option == 'version':  #当命令行参数为-- version,显示版本号
21         print('Version 1.2')
22     elif option == 'help':  #当命令行参数为--help时,显示相关帮助内容
23         print('''  
24 This program prints files to the standard output.    
25 Any number of files can be specified.    
26 Options include:    
27   --version : Prints the version number    
28   --help    : Display this help''')
29     else:
30         print('Unknown option.')
31     sys.exit()
32 else:
33     for filename in sys.argv[1:]: #当参数为文件名时,传入readfile,读出其内容
34         readfile(filename)

上面的脚本名称在我的系统文件中命名为os_func.py(虽然没对应好,但懒得改了)。同时在os_func.py文件的同一目录下,新建文件test.txt.

在CMD中运行os_func.py脚本:

1.直接运行os_func.py脚本,返回os_func.py的路径。

上面的代码执行的为是脚本中的这一段内容:

 2.运行os_func.py脚本时,在后面加上参数 --version

 

上面的命令执行的是脚本中的当传入的参数大于等于2时,sys.argv[1]中的参数为‘--version',对字符串进行截取,判断截取的为'version'后,执行相应命令。

 

3.下面的命令执行原理同上2

 4.在执行 os_func.py后面加上文件名(可以叠加:python os_func.py test.txt test2.txt test3.txt)会执行相应的脚本内容,读取文件内容

 上面的命令执行的是脚本中的当传入的参数判断为文件名。

 sys.exit([arg])

 官方文档:

sys.exit([arg])

Exit from Python. This is implemented by raising the SystemExit exception, so cleanup actions specified by finally clauses of try statements are honored, and it is possible to intercept the exit attempt at an outer level.

The optional argument arg can be an integer giving the exit status (defaulting to zero), or another type of object. If it is an integer, zero is considered “successful termination” and any nonzero value is considered “abnormal termination” by shells and the like. Most systems require it to be in the range 0–127, and produce undefined results otherwise. Some systems have a convention for assigning specific meanings to specific exit codes, but these are generally underdeveloped; Unix programs generally use 2 for command line syntax errors and 1 for all other kind of errors. If another type of object is passed, None is equivalent to passing zero, and any other object is printed to stderr and results in an exit code of 1. In particular, sys.exit("some error message") is a quick way to exit a program when an error occurs.

Since exit() ultimately “only” raises an exception, it will only exit the process when called from the main thread, and the exception is not intercepted.

Changed in version 3.6: If an error occurs in the cleanup after the Python interpreter has caught SystemExit (such as an error flushing buffered data in the standard streams), the exit status is changed to 120.

 可选参数[arg],默认为0,可以通过传入不同的整数或其他指定参数作为指定不同的退出状态。如果传入的是整数,0代表“成功终止”,任何非零值在shell中被认为是“异常终止”。大多数系统要求它在0 - 127范围内,否则就生成未定义的结果。有些系统有一种约定,可以为特定的退出代码分配特定的含义,但是这些通常不发达;Unix程序通常使用2来表示命令行语法错误,1用于所有其他类型的错误。如果传递了另一种类型的对象,则没有一种对象是通过0传递的,任何其他对象都被打印到stderr中,结果为1的退出码。特别是,系统。退出(“一些错误消息”)是在错误发生时退出程序的快速方法。

由于退出()最终只引发了一个异常,它只会在从主线程调用时退出进程,并且不拦截异常。 

在版本3.6中更改的部分:如果在Python解释器捕获SystemExit之后的清理中出现错误(例如在标准流中的错误刷新缓冲数据),退出状态将更改为120

 

 

sys.version

A string containing the version number of the Python interpreter plus additional information on the build number and compiler used. This string is displayed when the interactive interpreter is started. Do not extract version information out of it, rather, use version_info and the functions provided by the platform module.

 

包含Python解释器的版本号,以及用于构建数字和编译器的附加信息的字符串。这个字符串在交互式解释器启动时显示。不要从中提取版本信息,而是使用版本信息和平台模块提供的功能提取版本信息。

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.

See also

Module site This describes how to use .pth files to extend sys.path.
 

sys.path()返回指定模块搜索路径的字符串列表。从环境变量PYTHONPATH初始化,并依赖于安装的默认值。

 

在程序启动时初始化时,该列表的第一项(path[0])是包含用于调用Python解释器的脚本的目录。如果脚本目录不可用(例如,如果解释器是交互调用的,或者如果脚本是从标准输入中读取的),那么path[0]是空字符串,它会将Python定向到当前目录中的搜索模块。注意,脚本目录插入到插入的条目之前,是python路径的结果。
 
 

由于在cmd中运行python的交互环境,没有执行相应的python脚本,故path[0]返回的值为'[]',返回一个空字符串。

 
 
sys.maxsize

An integer giving the maximum value a variable of type Py_ssize_t can take. It’s usually 2**31 1 on a 32-bit platform and 2**63 1 on a 64-bit platform.

一个整数,给出了一个Py_ssize_t类型变量的最大值。在32位平台上它通常是2 * * 31 - 1,在64位平台上它通常是2 * * 63 - 1。

 

sys.platform

This string contains a platform identifier that can be used to append platform-specific components to sys.path, for instance.

For Unix systems, except on Linux, this is the lowercased OS name as returned by uname -s with the first part of the version as returned by uname -r appended, e.g. 'sunos5' or 'freebsd8'at the time when Python was built. Unless you want to test for a specific system version, it is therefore recommended to use the following idiom:

if sys.platform.startswith('freebsd'):
    # FreeBSD-specific code here...
elif sys.platform.startswith('linux'):
    # Linux-specific code here...

For other systems, the values are:

Systemplatform value
Linux 'linux'
Windows 'win32'
Windows/Cygwin 'cygwin'
Mac OS X 'darwin'

Changed in version 3.3: On Linux, sys.platform doesn’t contain the major version anymore. It is always 'linux', instead of 'linux2' or 'linux3'. Since older Python versions include the version number, it is recommended to always use the startswith idiom presented above.

See also 

os.name has a coarser granularity. os.uname() gives system-dependent version information.

The platform module provides detailed checks for the system’s identity.

 

  

 

原文地址:https://www.cnblogs.com/zoe233/p/7116187.html