标准库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.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):
import sys
def readfile(filename): #定义readfile函数,从文件中读出文件内容
'''''''''Print a file to the standard output.'''
f = open('test.txt')
while True:
line = f.readline()
if len(line) == 0:
break
print(line,)# notice comma 分别输出每行内容 f.close()
# Script starts from here
print(sys.argv)
if len(sys.argv) < 2:
print('No action specified.')
sys.exit()
if sys.argv[1].startswith('--'):
option = sys.argv[1][2:]
# fetch sys.argv[1] but without the first two characters
if option == 'version': #当命令行参数为-- version,显示版本号
print('Version 1.2')
elif option == 'help': #当命令行参数为--help时,显示相关帮助内容
print('''
This program prints files to the standard output.
Any number of files can be specified.
Options include:
--version : Prints the version number
--help : Display this help''')
else:
print('Unknown option.')
sys.exit()
else:
for filename in sys.argv[1:]: #当参数为文件名时,传入readfile,读出其内容
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.
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_tcan take. It’s usually2**31 - 1on a 32-bit platform and2**63 - 1on 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:
| System | platformvalue | 
|---|---|
| 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.
标准库sys的更多相关文章
- Python——标准库  Sys模块
		---------------------------------------------------------------------------------------------------- ... 
- Python3 标准库:sys
		import sys print(sys.argv[0]) print(sys.argv[1]) print(len(sys.argv)) print(str(sys.argv)) print(sys ... 
- Python标准库sys
		1.命令行参数sys.argv 我们从Python语言之模块第一部分的例子开始,看看sys.argv中到底存了些什么内容. #Filename: using_sys.py import sys i=0 ... 
- A Byte of Python 笔记(12)python 标准库:sys、os,更多内容
		第14章 python 标准库 Python标准库是随Python附带安装的,它包含大量极其有用的模块. sys 模块 sys 模块包含系统对应的功能.如 sys.argv 列表包含命令行参数. # ... 
- python基础课程_学习笔记13:标准库:有些收藏夹——sys
		标准库:有些收藏夹 sys sys这个模块可以让你访问和python解释器联系紧密的变量和函数. sys模块中一些重要的函数和变量 函数/变量 描写叙述 argv 命令行參数,包含脚本名称 exit( ... 
- 介绍下Python的两个标准库 os 和 sys
		import sysprint(sys.path) #python 2 中报错 ....,打印的是绝对路径(***\\python\\lib\\site-packages# 第三方库,后退一级为标准库 ... 
- python练习 - 系统基本信息获取(sys标准库)+ 二维数据表格输出(tabulate库)
		系统基本信息获取 描述 获取系统的递归深度.当前执行文件路径.系统最大UNICODE编码值等3个信息,并打印输出. ... 
- python标准库00 学习准备
		Python标准库----走马观花 python有一套很有用的标准库.标准库会随着python解释器一起安装在你的电脑上的.它是python的一个组成部分.这些标准库是python为你准备的利器,可以 ... 
- 【循序渐进学Python】11.常用标准库
		安装完Python之后,我们也同时获得了强大的Python标准库,通过使用这些标准库可以为我们节省大量的时间.这里是一些常用标准库的简单说明.更多的标准库的说明,可以参考Python文档 sys 模块 ... 
随机推荐
- CAS / ABA
			CAS / ABA 标签(空格分隔): 操作系统 1. CAS 解决 Volatile 不保证原子性的问题 /** * Atomically increments by one the current ... 
- /usr/lib/jvm/java-1.8.0-openjdk/release 没有这个文件或目录
			在Java1.8以上,安装以后再安装目录是自动生成一个release文件,用于记录Java和系统信息.但是在centos中,如果你的Java是在安装系统时选择自动安装的,那么在标题那个目录下,也就是j ... 
- Linux学习,账号管理与权限管理
			linux系统本来不认识账号,只是通过UID(用户ID)和GID(所属组ID)来区分账号属性的.而这对应的目录如下: UID ===> /etc/passwd GID ===> /etc/ ... 
- Python 的while循环和for循环的使用
			#循环 遍历 迭代 # while循环 a = 0while a <5: a =a+1 if a == 3: continueprint('我循环了')+str(a) # print ('我循环 ... 
- Java 方法之形参和实参 、堆、栈、基本数据类型、引用数据类型
			* 形式参数:用于接收实际参数的变量(形式参数一般就在方法的声明上) * 实际参数:实际参与运算的变量 * 方法的参数如果是基本数据类型:形式参数的改变不影响实际参数. * * 基本数据类型:byte ... 
- C++实现双向循环链表
			本次博文是关于利用C++模板的方式实现的双向循环链表以及双向循环链表的基本操作,在之前的博文C++语言实现双向链表中,已经给大家分析了双向循环链表的结构,并以图示的方式给大家解释了双向循环链表的基本操 ... 
- NonRegisteringDriver造成的内存频繁FullGc
			某天上服务器看了下gc情况,发现状况不对,启动了才2天的服务器发生了360次fullgc,这个频率肯定高了 说明 S0C.S1C.S0U.S1U:Survivor 0/1区容量(Capacity)和使 ... 
- React Native简史
			诞生 React Native 诞生于 2013 年的 Facebook 内部黑客马拉松(hackathon): In the essence of Facebook’s hacker culture ... 
- go中的error小结
			go中的error error和panic error接口 go中err的困局 推荐方法 总结 参考 go中的error go中的错误处理,是通过返回值的形式来出来,要么你忽略,要么你处理(处理也可以 ... 
- 【three.js第三课】鼠标事件,移动、旋转物体
			1.下载three.js的源码包后,文件夹结构如下: 2.在[three.js第一课]的代码基础上,引入OrbitControls.js文件,此文件主要用于 对鼠标的操作. 该文件位置:在文件结构中 ... 
