Python(2.7)-标准输入输出,标准错误输出

sys模块,标准输入,标准输出和标准错误输出

1、标准输入sys.stdin:对应的操作是input

sys.stdin.readline():只输入(获取)一行,sys.stdin.readline()会将标准输入全部获取,包括末尾的' ',所以一般会在末尾加上.strip()或.strip(“ ”)去掉末尾的换行符

>>> 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() :将输入的内容全部获取,以字符串的形式输出,行与行之间用” ”分隔

>>>import sys

>>> sys.stdin.read()

123

456

56756

^Z

'123 456 56756 '

>>> 

sys.stdin.readlines() :获取所有输入信息,以列表输出,每一行是一个元素,每行末尾带换行符

>>>import sys

>>> sys.stdin.readlines()

abc

hello ads

sadjf

exit

^Z            #Ctrl+z 终止输入

['abc ', 'hello ads ', 'sadjf ', 'exit ']

>>> 

2、标准输出sys.stdout,对应的操作是print;只需要定义一个write对象,告诉sys.stdout去哪儿写

sys.stdout.write ():从键盘读取sys.stdout.write ()输入的内容,默认不会换行,所以一般会在末尾加上“ ”,跟print方法类似

>>>import sys

>>> sys.stdout.write("pangwei")

pangwei>>> sys.stdout.write("pangwei ")

pangwei

>>> 

>>> for i in range(3):

...     sys.stdout.write("pangwei ")

...

pangwei

pangwei

pangwei

>>> 

3.标准错误输出(sys.stderr)和标准输出类似也是print(打印),可以写入文件中

>>> import sys

>>> sys.stderr.write("error ")

error

>>> sys.stderr=open("d:\error.txt","w")

>>> sys.stderr.write("pangwei ")

>>> 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)

原文地址:https://www.cnblogs.com/pw20180101/p/8330535.html