Python3之sys模块

Python常用模块之sys

sys模块提供了一系列有关Python运行环境的变量和函数。

sys模块的常见函数列表

  • sys.argv: 实现从程序外部向程序传递参数。

    作用:在终端运行py文件+传入参数 可以通过该方法获取到值

  实例: 

#获取脚本名字
import sys
print(sys.argv[0])

#结果
/Users/pengbin/PycharmProjects/S01/Atm/atm/main.py
  • sys.exit([arg]):程序中间的退出,arg=0为正常退出。

 

    作用: sys.exit() 可以强制中途退出程序,当参数值非0时会抛出一个异 SystemExit ,可以捕获这个异常继续对文件进行操作

  实例

import sys

def exitfunc(value):
    print( value)
    sys.exit(0)#退出程序

print( "hello")

try:
    sys.exit(1)#抛出异常SystemExit
except SystemExit as value:
    print('异常捕获!')
    exitfunc(value)

print ("come?")
  • sys.getdefaultencoding(): 获取系统当前编码,一般默认为ascii。]

 

  • sys.path: 获取指定模块搜索路径的字符串集合,可以将写好的模块放在得到的某个路径下,就可以在程序中import时正确找到。

  作用:可以把自定义的模块加入到path集合中

  实例: 

# 在path的开始位置 插入test
>>> sys.path.insert(0,'test')
>>> sys.path
['test', '', 'E:\\Python27\\Lib\\idlelib', 'C:\\Windows\\system32\\python27.zip', 'E:\\Python27\\DLLs', 'E:\\Python27\\lib', 'E:\\Python27\\lib\\plat-win', 'E:\\Python27\\lib\\lib-tk', 'E:\\Python27', 'E:\\Python27\\lib\\site-packages']
# 可以成功import test
>>> import test
# 找不到 other 这个模块
>>> import other
Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
    import other
ImportError: No module named other
# 需要添加path
>>> sys.path.insert(0,'other')
>>> import other
  • sys.platform获取当前执行环境的平台,如win32表示是Windows 32bit操作系统,linux2表示是linux平台;
# linux 
>>> import sys
>>> sys.platform
'linux2'

# windows
>>> import sys
>>> sys.platform
'win32'

  …………跟多方法后面更新……

posted @ 2017-08-17 15:20  Ronny_bin  阅读(120)  评论(0)    收藏  举报