sys模塊,標准輸入,標准輸出和標准錯誤輸出
1、標准輸入sys.stdin:對應的操作是input
sys.stdin.readline():只輸入(獲取)一行,sys.stdin.readline()會將標准輸入全部獲取,包括末尾的'\n',所以一般會在末尾加上.strip()或.strip(“\n”)去掉末尾的換行符
>>> import sys
>>> line=sys.stdin.readline() #末尾不加.strip()
123 #末尾有一個換行符
>>> for i in range(len(line)): #len(line)=4
... print line[i]+"hello"
...
1hello
2hello
3hello
hello #末尾不加.strip(),由於換行符會多一個空行(”/nhello”)
>>> print line
123
>>> line=sys.stdin.readline().strip() #末尾加.strip() ,去掉了換行符
123
>>> for i in range(len(line)): #len(line)=3
... print line[i]+"hello"
...
1hello
2hello
3hello
>>>
sys.stdin.read() :將輸入的內容全部獲取,以字符串的形式輸出,行與行之間用”\n”分隔
>>>import sys
>>> sys.stdin.read()
123
456
56756
^Z
'123\n456\n56756\n'
>>>
sys.stdin.readlines() :獲取所有輸入信息,以列表輸出,每一行是一個元素,每行末尾帶換行符
>>>import sys
>>> sys.stdin.readlines()
abc
hello ads
sadjf
exit
^Z #Ctrl+z 終止輸入
['abc\n', 'hello ads\n', 'sadjf\n', 'exit\n']
>>>
2、標准輸出sys.stdout,對應的操作是print;只需要定義一個write對象,告訴sys.stdout去哪兒寫
sys.stdout.write ():從鍵盤讀取sys.stdout.write ()輸入的內容,默認不會換行,所以一般會在末尾加上“\n”,跟print方法類似
>>>import sys
>>> sys.stdout.write("pangwei")
pangwei>>> sys.stdout.write("pangwei\n")
pangwei
>>>
>>> for i in range(3):
... sys.stdout.write("pangwei\n")
...
pangwei
pangwei
pangwei
>>>
3.標准錯誤輸出(sys.stderr)和標准輸出類似也是print(打印),可以寫入文件中
>>> import sys
>>> sys.stderr.write("error\n")
error
>>> sys.stderr=open("d:\\error.txt","w")
>>> sys.stderr.write("pangwei\n")
>>> sys.stderr.flush(0) #錯誤信息會被寫入文件,如下
>>>
#執行結果(error.txt文件內容)
pangwei
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: flush() takes no arguments (1 given)