python常用模块之sys模块
1.sys.argv[]
:命令行参数List,第一个元素是程序本身
# 写一个简单的python程序,代码如下:
#!/usr/bin/python
#coding=utf8
"""
Author: xiaoyafei
Created Time : 2018-05-09 14:57:36
File Name: argvTest.py
"""
import sys
print(sys.argv[0])
print(sys.argv[1])
print(sys.argv[2])
# 去执行这个程序
[root@host-10-200-137-195 tmp]# python3 argvTest.py old_str new_str
argvTest.py # 第0个是函数本身
old_str # 第一个
new_str # 第二个
2.sys.exit()
:退出程序,正常退出是sys.exit(0)
In [1]: import sys
In [2]: sys.exit("bye")
An exception has occurred, use %tb to see the full traceback.
SystemExit: bye # 会打印个bye然后退出
/usr/local/lib/python3.6/site-packages/IPython/core/interactiveshell.py:2918: UserWarning: To exit: use 'exit', 'quit', or Ctrl-D.
warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)
In [2]: sys.exit(0)
An exception has occurred, use %tb to see the full traceback.
SystemExit: 0
/usr/local/lib/python3.6/site-packages/IPython/core/interactiveshell.py:2918: UserWarning: To exit: use 'exit', 'quit', or Ctrl-D.
warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)
3.sys.version()
:获取python解释程序的版本信息
In [3]: sys.version
Out[3]: '3.6.4 (default, Mar 22 2018, 13:40:22) \n[GCC 4.8.5 20150623 (Red Hat 4.8.5-16)]'
4.sys.maxsize
:最大的Int值
In [9]: sys.maxsize
Out[9]: 9223372036854775807
5.sys.path
:返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
In [10]: sys.path # 既然是列表那就可以使用append()进行追加
Out[10]:
['',
'/usr/local/bin',
'/usr/local/lib/python36.zip',
'/usr/local/lib/python3.6',
'/usr/local/lib/python3.6/lib-dynload',
'/usr/local/lib/python3.6/site-packages',
'/usr/local/lib/python3.6/site-packages/pip-1.5.4-py3.6.egg',
'/usr/local/lib/python3.6/site-packages/IPython/extensions',
'/root/.ipython']
6.sys.platform
:返回操作系统平台名称
In [11]: sys.platform
Out[11]: 'linux'
7.sys.stdout.write()
:标准输出
In [3]: sys.stdout.write('please:')
Out[3]: please:7
8.sys.stdin.readline()[:-1]
:标准输入
In [4]: sys.stdin.readline()[:-1] # 等待用户输入,直到\n,也可以使用read函数(会一直让用户输入)
abc
Out[4]: 'abc'
9.sys.getrecursionlimit()
:获取最大递归深度
In [6]: sys.getrecursionlimit()
Out[6]: 3000
10.``:修改递归最大深度
In [7]: sys.setrecursionlimit(1500)
In [8]: sys.getrecursionlimit()
Out[8]: 1500
11.sys.getdefaultencoding()
:获取解释器默认编码
In [9]: sys.getdefaultencoding() # Linux默认是UTF-8
Out[9]: 'utf-8'
12.sys.getfilesystemencoding()
:获取内存数据存在文件的默认编码
In [10]: sys.getfilesystemencoding() #
Out[10]: 'utf-8' # 指的是操作系统里的文件系统