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'#這一行輸出到控制台

 未完待續……


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM