Python常用模块之sys

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

常见用法

  • sys.argv

    可以用sys.argv获取当前正在执行的命令行参数的参数列表(list)。
变量 解释
sys.argv[0] 当前程序名
sys.argv[1] 第一个参数
sys.argv[0] 第二个参数

参考代码:

# encoding: utf-8
# filename: argv_test.py
import sys # 获取脚本名字
print 'The name of this program is: %s' %(sys.argv[0])
# 获取参数列表
print 'The command line arguments are:'
for i in sys.argv:
print i
# 统计参数个数
print 'There are %s arguments.'%(len(sys.argv)-1)

运行结果:

E:\p>python argv_test.py arg1 arg2 arg3
The name of this program is: argv_test.py
The command line arguments are:
argv_test.py
arg1
arg2
arg3
There are 3 arguments.
  • sys.platform

获取当前执行环境的平台,如win32表示是Windows 32bit操作系统,linux2表示是linux平台;

# linux
>>> import sys
>>> sys.platform
'linux2' # windows
>>> import sys
>>> sys.platform
'win32'
  • sys.path

path是一个目录列表,供Python从中查找第三方扩展模块。在python启动时,sys.path根据内建规则、PYTHONPATH变量进行初始化。

>>> sys.path
['', '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']

有时候为了让python能够找到我们自己定义的模块,需要修改sys.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.path.append(“mine module path”)来添加自定义的module。

  • sys.builtin_module_names

sys.builtin_module_names返回一个列表,包含内建模块的名字。如:

>>> import sys
>>> print sys.builtin_module_names
('__builtin__', '__main__', '_ast', '_bisect', '_codecs', '_codecs_cn', '_codecs_hk', '_codecs_iso2022', '_codecs_jp', '_codecs_kr', '_codecs_tw', '_collections', '_csv', '_functools', '_heapq', '_hotshot', '_io', '_json', '_locale', '_lsprof', '_md5', '_multibytecodec', '_random', '_sha', '_sha256', '_sha512', '_sre', '_struct', '_subprocess', '_symtable', '_warnings', '_weakref', '_winreg', 'array', 'audioop', 'binascii', 'cPickle', 'cStringIO', 'cmath', 'datetime', 'errno', 'exceptions', 'future_builtins', 'gc', 'imageop', 'imp', 'itertools', 'marshal', 'math', 'mmap', 'msvcrt', 'nt', 'operator', 'parser', 'signal', 'strop', 'sys', 'thread', 'time', 'xxsubtype', 'zipimport', 'zlib')

代码示例:

# encoding: utf-8
# find_module.py import sys # print sys.builtin_module_names def find_module(module):
if module in sys.builtin_module_names:
print module," => ","__builtin__"
else:
print module,"=> ",__import__(module).__file__ find_module('os')
find_module('sys')
find_module('strop')
find_module('zlib')
find_module('string') # 运行结果:
>>>
======================== RESTART: E:/p/find_module.py ========================
os => E:\Python27\lib\os.pyc
sys => __builtin__
strop => __builtin__
zlib => __builtin__
string => E:\Python27\lib\string.pyc
  • sys.exit(n)

调用sys.exit(n)可以中途退出程序,当参数非0时,会引发一个SystemExit异常,从而可以在主程序中捕获该异常。

看代码:

# encoding: utf-8
import sys print 'running...' try:
sys.exit(1)
except SystemExit:
print 'SystemExit exit 1' print 'exited'

运行结果:

>>>
======================= RESTART: E:/p/sys_exit_test.py =======================
running...
SystemExit exit 1
exited

也可以自定义exitfunc方法,用于程序退出前调用,进行一些清理动作。

详细可以参考Python sys.exitfunc Examples

Python常用模块之sys的更多相关文章

  1. python常用模块之sys模块

    python常用模块之sys模块 1.sys.argv[]:命令行参数List,第一个元素是程序本身 # 写一个简单的python程序,代码如下: #!/usr/bin/python #coding= ...

  2. python - 常用模块 os, sys

    常用模块: os(处理文件和目录), sys(sys 模块包含了与 Python 解释器和它的环境有关的函数.) sys.argv 变量是一个字符串的 列表.特别地,sys.argv 包含了 命令行参 ...

  3. python常用模块:sys、os、path、setting、random、shutil

    今日内容讲了3个常用模块 一.sys模块二.os模块三.os下path模块四.random模块五.shutil模块 一.sys模块 import sys #环境变量 print(sys.path) # ...

  4. Python常用模块os & sys & shutil模块

    OS模块 import os ''' os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径 os.chdir("dirname") 改变当前脚本工作目录: ...

  5. python常用模块之sys, os, random

    一. sys模块 1. 作用: sys模块是与python解释器交互的一个接口 2. 具体使用 1. sys.argv 获取当前正在执行的命令行列表, 第一个为程序本身路径 print('file n ...

  6. Python常用模块【sys】

    sys.argv 参数    「argv」是「argument variable」参数变量的简写形式.一般在命令行调用的时候由系统传递给程序.这个变量其实是一个List列表,argv[0] 一般是“被 ...

  7. Python常用模块——目录

    Python常用模块学习 Python模块和包 Python常用模块time & datetime &random 模块 Python常用模块os & sys & sh ...

  8. python 常用模块之random,os,sys 模块

    python 常用模块random,os,sys 模块 python全栈开发OS模块,Random模块,sys模块 OS模块 os模块是与操作系统交互的一个接口,常见的函数以及用法见一下代码: #OS ...

  9. python 常用模块 time random os模块 sys模块 json & pickle shelve模块 xml模块 configparser hashlib subprocess logging re正则

    python 常用模块 time random os模块 sys模块 json & pickle shelve模块 xml模块 configparser hashlib  subprocess ...

随机推荐

  1. ural 2066. Simple Expression

    2066. Simple Expression Time limit: 1.0 secondMemory limit: 64 MB You probably know that Alex is a v ...

  2. Hive内部表外部表转化分析(装)

    link:http://anyoneking.com/archives/127hive表分为内部表和外部表.外部表在删除的时候并不会删除到hdfs中的文件,比较安全,所以对于重要的需要进行分析的日志建 ...

  3. 自定义Toast、程序退出时Toast也退出、Toast的用法

    http://blog.csdn.net/wangqilin8888/article/details/7464806 当我们在一个应用中用到Toaster来做为提示时,发现这样一个问题,当某个条件服合 ...

  4. 关于使用rem单位,calc()进行自适应布局

    关于css中的单位 大家都知道在css中的单位,一般都包括有px,%,em等单位,另外css3新增加一个单位rem. 其中px,%等单位平时在传统布局当中使用的比较频繁,大家也比较熟悉,不过px单位在 ...

  5. CentOS6.4 安装nmon

    安装 mkdir /usr/local/nmon cd /usr/local/nmon wget http://sourceforge.net/projects/nmon/files/nmon_lin ...

  6. URAL 1501. Sense of Beauty(记忆化搜索)

    题目链接 本来暴力写个TLE了,加上记忆化就A了. #include <cstring> #include <cstdio> #include <string> # ...

  7. spring源码学习之路---深度分析IOC容器初始化过程(四)

    作者:zuoxiaolong8810(左潇龙),转载请注明出处,特别说明:本博文来自博主原博客,为保证新博客中博文的完整性,特复制到此留存,如需转载请注明新博客地址即可. 最近由于工作和生活,学习耽搁 ...

  8. PL/SQL无法连接,提示:pl/sql initialization error sql*net not properly installed

    各种找资料都不行,最后还是在公司的线上环境中去找不同点配置好的.不多说了,就做了如下配置: 服务器环境是:windows server 2008 64位操作系统 1.电脑系统环境变量PATH增加:x: ...

  9. 关于Repeater嵌套绑定的问题

    前台代码: <div id="firstpane" class="menu_list">                <asp:Repeat ...

  10. Win7 系统下 Firefox hostadmin插件无法修改Host

    问题:  win 7系统,今天用杀毒软件杀了一下毒,firefox hostAdmin插件无法修改Host了,提示“ write hosts file failed check permissions ...