python标准库sys模块常用函数

 

一、stdin:从标准输入读入数据

script.py

import sys
text = sys.stdin.read()
words = text.split()
for i in words:
    print i

cat source.txt | script.py | sort

二、argv:获取程序外部向程序传递的参数

script.py

import sys
print sys.argv[0]
print sys.argv[1]

python script.py arg1 arg2

三、exit():退出当前进程

scrpit.py

复制代码

import sys

def exitfunc(value):
    print value
    sys.exit(0)

print "hello"

try:
    sys.exit(1)
except SystemExit,value:
    exitfunc(value)

print "come?"

复制代码

python script.py

四、stdout

这个有点复杂

首先介绍一下stdout与print 的区别

print 将你需要的内容打印到了控制台,然后追加了一个换行符

print 会调用 sys.stdout 的 write 方法

下边两行结果是一样的:

sys.stdout.write('hello'+'\n')
print 'hello'

sys.stdout指向控制台,如果将文件对象的引用赋值给sys.stdout,那么就会输出到文件。如果输出到文件之后还想在控制台输出内容,那么应该将控制台的对象引用保存下来。

复制代码

# -*- coding = UTF-8 -*-
import sys
f_handler = open('out.log','w')
__console__ = sys.stdout
sys.stdout = f_handler
print 'hello'#这一行将会输出到文件,和调用文件的write方法相同
sys.stdout = __console__
print 'hello'#这一行输出到控制台

复制代码

猜你喜欢

转载自blog.csdn.net/liangjiubujiu/article/details/81210822