Python常用模块之sys

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

1 )、 sys.stdin 标准输入流。
2 )、sys.stdout 标准输出流。
3 )、 sys.stderr 标准错误流。
4 )、 sys.path 查找模块所在目录的目录名列表。
5 )、 sys.argv 命令行的参数,包括脚本名称。
6 )、 sys.platform 返回当前系统平台,如:win32、Linux等。
7 )、 sys.exit(n)  退出程序,正常退出时exit(0)
8 )、 sys.version  获取Python解释器的版本信息
10 )、 sys.maxint  最大的Int值
11 )、 stdout.writr('please;')
12 )、 val = sys.stdin.readlin()[:-1]

常见用法

  • 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

pyhton3 sys模块的更多相关文章

  1. python常用模块(模块和包的解释,time模块,sys模块,random模块,os模块,json和pickle序列化模块)

    1.1模块 什么是模块: 在计算机程序的开发过程中,随着程序代码越写越多,在一个文件里代码就会越来越长,越来越不容易维护. 为了编写可维护的代码,我们把很多函数分组,分别放到不同的文件里,这样,每个文 ...

  2. python标准模块(os及sys模块)

    一.os模块 用于提供系统级别的操作 os.getcwd() 获取当前工作目录 os.stat('path/filename') 获取文件/目录信息,其中包括文件大小等 os.sep 获得操作系统特定 ...

  3. [转载]python中的sys模块(二)

    #!/usr/bin/python # Filename: using_sys.py import sys print 'The command line arguments are:' for i ...

  4. [转载]Python中的sys模块

    #!/usr/bin/python # Filename: cat.py import sys def readfile(filename): '''Print a file to the stand ...

  5. python之sys模块详解

    python之sys模块详解 sys模块功能多,我们这里介绍一些比较实用的功能,相信你会喜欢的,和我一起走进python的模块吧! sys模块的常见函数列表 sys.argv: 实现从程序外部向程序传 ...

  6. sys模块和os模块,利用sys模块生成进度条

    sys模块import sysprint(sys.argv)#sys.exit(0)             #退出程序,正常退出exit(0)print(sys.version)       #获取 ...

  7. os和sys模块

    sys模块 sys模块主要是用于提供对python解释器相关的操作 函数 sys.argv #命令行参数List,第一个元素是程序本身路径 sys.path #返回模块的搜索路径,初始化时使用PYTH ...

  8. python中os和sys模块的详解

    平时在工作中经常会用到os模块和sys模块的一些特性,下面是这些特性的一些相关解释,希望对大家有所帮助 os模块 os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径 os. ...

  9. Python学习总结12:sys模块

    sys模块常用来处理Python运行时配置以及资源,从而可以与前当程序之外的系统环境交互. 1. 导入及函数查看 >>> import sys #导入sys模块 >>&g ...

随机推荐

  1. 在python中配置tornado服务

    import tornado.httpserver import tornado.options import tornado.web from tornado.options import defi ...

  2. Yii简单使用阿里云短信教程!

    首先我们下载官方完整包的SDK官方标明了啊,PHP版本一定要不低于5.5下载后目录如下: 我们只需要将目录里的api_sdk复制出来到Yii项目的根目录的common模块下面的extensions文件 ...

  3. Unity官方发布热更新方案性能对照

    孙广东  2016.3.11 Unity应用的iOS热更新 作者:丁治宇 Unity TechnologiesChina Agenda •  什么是热更新 •  为何要热更新 •  怎样在iOS 上对 ...

  4. Unity3D学习笔记——NGUI之UIScrollView

    前言:有的时候Panel会被截取,里面的内容就不能显示完整,所以需要为其添加 scroll view组件. 一:将Panel放进一个scroll view只需要简单的3步: 1.首先在UI Root下 ...

  5. CStdioFile UNICODE编译 读取中文汉字乱码 .

    函数原形为:char *setlocale( int category, const char *locale );头文件:<locale.h>所支持的操作系统为:ANSI, Win 95 ...

  6. PHP中常用的输出语句比较?

    面试中经常问到这个,可以看下. 面试问题:比较echo print() print_r()  var_dump()? echo(): 可以一次输出多个值,多个值之间用逗号分隔.echo是语言结构(la ...

  7. python3基础知识学习记录

    学习地址:http://www.runoob.com/python3/python3-tutorial.html ------------------------------ 为什么要学python: ...

  8. Happy Necklace(矩阵快速幂)

    Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 131072/131072 K (Java/Others) Total Submissi ...

  9. 关于angularjs的ng-repeat指令

    (如果有说的不对,欢迎指教,更欢迎大家一起交流.) 关于angularjs的ng-repeat指令,想必每个学习angularjs的初学者都很有映像.那我也总结一下我使用ng-repeat的时候经验, ...

  10. js引入方式的弹框方法2

    html代码: <!DOCTYPE html> <html lang="zh-CN"> <head> <meta http-equiv=& ...