博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python之sys模块小探
阅读量:2188 次
发布时间:2019-05-02

本文共 4802 字,大约阅读时间需要 16 分钟。

Sys模块函数之多,我只能选取自己认为比较实用的一些函数列在此处。借马云找员工的说法,”找最合适的而不是最天才的”,这句话,我个人觉得在很多方面都能适应,学习也不在话下。Sys模块功能的确很多,但我们应该将重点放在那些功能才是最适合我们的,为此,我列的这些函数,就是我认为比较适合我以后开发的函数。

(1)sys.argv

很多人会想,我如何给我的程序在外部传递参数呢?这个,就可以实现。如:
Tesy.py
Import sys
Print sys.argv[number]
一般情况下,number为0是这个脚本的名字,1,2…则为命令行下传递的参数.如:
Test.py脚本内容:
import sys
 
print sys.argv[0]
print sys.argv[1]
print sys.argv[2]
print sys.argv[3]
那么
[root@databak scripts]# python test.py arg1arg2 arg3
test.py
arg1
arg2
arg3
看到,对应的关系了吗?还有,在python.org模块参考手册说,如果在命令行下选用-c那么argv[0]= -c 看下,
[root@databak scripts]# python -c"import sys;print sys.argv[0];print sys.argv[1]" arg1
-c
arg1
如果大家不明白,可以参考下man python
SYNOPSIS
      python [ -d ] [ -E ] [ -h ] [ -i ] [ -m module-name ] [ -O ]
              [ -Q argument ] [ -S ] [ -t ] [-u ]
              [ -v ] [ -V ] [ -W argument ] [-x ]
             
[ -ccommand | script | - ] [ arguments ]

(2)sys.platform

大家都知道,当今的程序比较流行的是跨平台。简单的说就是这段程序既可以在
windows
下,换到
linux
下也可以不加修改的运行起来,听起来就不错。所以,这个函数就可以派上用场了。
假设,我们想实现一个清除终端,
linux
下用
clear, windows
下用
cls
Ostype=sys.platform
If ostype==”linux” orostype==”linux2”:
Cmd=”clear”
Else:
  Cmd=”cls”

(3) sys.exit(n)

执行至主程序的末尾时,解释器会自动退出. 但是如果需要中途退出程序, 你可以调用sys.exit 函数, 它带有一个可选的整数参数返回给调用它的程序. 这意味着你可以在主程序中捕获对sys.exit 的调用。(注:0是正常退出,其他为不正常,可抛异常事件供捕获!)
import sys
 
def exitfunc(value):
    '''Clear function'''
    print value
    sys.exit(0)
 
print "hello"
 
try:
    sys.exit(1)
except SystemExit,value:
    exitfunc(value)
 
print "come?"
输出结果:
[root@databak scripts]# python test.py
hello
1
以下是python.org库参考手册中,摘抄来的,供参考。
Exit from Python. This is implemented byraising the exception, so cleanup actions specified by finally clauses of statements arehonored, and it is possible to intercept the exit attempt at an outer level.The optional argument
arg can be aninteger giving the exit status (defaulting to zero), or another type of object.If it is an integer, zero is considered “successful termination” and anynonzero value is considered “abnormal termination” by shells and the like. Mostsystems require it to be in the range 0-127, and produce undefined resultsotherwise. Some systems have a convention for assigning specific meanings tospecific exit codes, but these are generally underdeveloped; Unix programsgenerally use 2 for command line syntax errors and 1 for all other kind oferrors. If another type of object is passed, None isequivalent to passing zero, and any other object is printed to sys.stderrand results in an exit code of 1. In particular, sys.exit("some
error
message") is aquick way to exit a program when an error occurs.
 
大概意思是说,sys.exit从python程序中退出,将会产生一个systemExit异常,可以为此做些清除除理的工作。这个可选参数默认正常退出状态是0,以数值为参数的范围为:0-127。其他的数值为非正常退出,还有另一种类型,在这里展现的是strings对象类型。

(4)sys.path

大家对模块都有一定了解吧?大家在使用模块的某一个功能前,是不是需要导入呢?答案是需要。那import,__import__命令就不用提干嘛的了吧。那大家在执行import module_name的时候,python内部发生了什么呢?简单的说,就是搜索module_name。根据sys.path的路径来搜索module.name
>>> sys.path
['', '/usr/local/lib/python24.zip', '/usr/local/lib/python2.4','/usr/local/lib/python2.4/plat-freebsd4', '/usr/local/lib/python2.4/lib-tk','/usr/local/lib/python2.4/lib-dynload','/usr/local/lib/python2.4/site-packages']
大家以后写好的模块就可以放到上面的某一个目录下,便可以正确搜索到了。当然大家也可以添加自己的模块路径。Sys.path.append(“mine module path”).
 

(5)sys.modules

This is a dictionary that maps module names to modules which havealready been loaded. This can be manipulated to force reloading of modules andother tricks.
Python.org
手册里已经说的很明白了。
For names in sys.modules.keys():
If names != ’sys’:
    ……

(6)sys.stdin,sys.stdout,sys.stderr

stdin , stdout , 以及stderr 变量包含与标准I/O 流对应的流对象. 如果需要更好地控制输出,而print 不能满足你的要求, 它们就是你所需要的. 你也可以替换它们, 这时候你就可以重定向输出和输入到其它设备( device ), 或者以非标准的方式处理它们
从网上摘抄的文章,供大家参考:
#testingstdout
print 'Hello World!'
运行hello.py就会在标准输出的屏幕上打印 Hello World!, 我们再编一个简单的标准输入的小程序 sayhi.py:
#testing stdin
print 'Hi, %s!' %raw_input('Please enter your name:')
当你用键盘输入你的名字后,程序在屏幕上输出Hi,[你的名字]!, 这就是从标准输入:键盘获取信息,再输出到标准输出:屏幕的例子。
那么上面的例子中print 和 raw_input是如何与标准输入/输出流建立关系的呢?
其实Python程序的标准输入/输出/出错流定义在sys 模块中,分别 为: sys.stdin,sys.stdout, sys.stderr
上面的程序分别与下列的程序是一样的:
import sys
sys.stdout.write('HelloWorld!')
import sys
print 'Please enter yourname:',
name=sys.stdin.readline()[:-1]
print 'Hi, %s!' % name
那么sys.stdin, sys.stdout, stderr到底是什么呢?我们在Python运行环境中输入以下代码:
import sys
for f in (sys.stdin,sys.stdout, sys.stderr): print f
输出为:
<open file'<stdin>', mode 'r' at 892210>
<open file'<stdout>', mode 'w' at 892270>
<open file'<stderr>', mode 'w at 8922d0>
由此可以看出stdin, stdout, stderr在Python中无非都是文件属性的对象,他们在Python启动时 自动与Shell 环境中的标准输入,输出,出错关联。
而Python程序的在Shell中的I/O重定向与本文开始时举的DOS命令的重定向完全相同,其实这种重定向是由Shell来提供的,与Python 本身并无关系。那么我们是否可以在Python程序内部将stdin,stdout,stderr读写操作重定向到一个内部对象呢?答案是肯定的。
Python提供了一个StringIO模块来完成这个设想,比如:
from StringIO import StringIO
import sys
buff =StringIO()
temp =sys.stdout                              #保存标准I/O流
sys.stdout =buff                                #将标准I/O流重定向到buff对象
print 42, 'hello', 0.001
sys.stdout=temp                                #恢复标准I/O流
print buff.getvalue()

本文出自 “” 博客,请务必保留此出处

转载地址:http://tgwub.baihongyu.com/

你可能感兴趣的文章
Leetcode C++《热题 Hot 100-14》283.移动零
查看>>
Leetcode C++《热题 Hot 100-15》437.路径总和III
查看>>
Leetcode C++《热题 Hot 100-17》461.汉明距离
查看>>
Leetcode C++《热题 Hot 100-18》538.把二叉搜索树转换为累加树
查看>>
Leetcode C++《热题 Hot 100-19》543.二叉树的直径
查看>>
Leetcode C++《热题 Hot 100-21》581.最短无序连续子数组
查看>>
Leetcode C++《热题 Hot 100-22》2.两数相加
查看>>
Leetcode C++《热题 Hot 100-23》3.无重复字符的最长子串
查看>>
Leetcode C++《热题 Hot 100-24》5.最长回文子串
查看>>
Leetcode C++《热题 Hot 100-26》15.三数之和
查看>>
Leetcode C++《热题 Hot 100-28》19.删除链表的倒数第N个节点
查看>>
Leetcode C++《热题 Hot 100-29》22.括号生成
查看>>
Leetcode C++《热题 Hot 100-44》102.二叉树的层次遍历
查看>>
Leetcode C++《热题 Hot 100-47》236.二叉树的最近公共祖先
查看>>
Leetcode C++《热题 Hot 100-48》406.根据身高重建队列
查看>>
《kubernetes权威指南·第四版》第二章:kubernetes安装配置指南
查看>>
Leetcode C++《热题 Hot 100-49》399.除法求值
查看>>
Leetcode C++《热题 Hot 100-51》152. 乘积最大子序列
查看>>
Leetcode C++ 《第181场周赛-1》 5364. 按既定顺序创建目标数组
查看>>
Leetcode C++ 《第181场周赛-2》 1390. 四因数
查看>>