python中sys.stdout、sys.stdin

如果需要更好的控制输出,而print不能满足需求,sys.stdout,sys.stdin,sys.stderr就是你需要的。

1. sys.stdout与print:

在python中调用print时,事实上调用了sys.stdout.write(obj+'\n')

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

以下两行代码等价:

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

2. sys.stdin与input

sys.stdin.readline( )会将标准输入全部获取,包括末尾的'\n',因此用len计算长度时是把换行符'\n'算进去了的,但是input( )获取输入时返回的结果是不包含末尾的换行符'\n'的。

因此如果在平时使用sys.stdin.readline( )获取输入的话,不要忘了去掉末尾的换行符,可以用strip( )函数(sys.stdin.readline( ).strip('\n'))或sys.stdin.readline( )[:-1]这两种方法去掉换行。

import sys
hi1=input()
hi2=sys.stdin.readline()
print(len(hi1))
print(len(hi2))

结果如下:

PS C:\test> python 2.py
123
123
3
4

3. 从控制台重定向到文件

原始的sys.stdout指向控制台,如果把文件的对象引用赋给sys.stdout,那么print调用的就是文件对象的write方法。

import sys
sys.stdout = open('test.txt','w')
print 'Hello world'

恢复默认映射

import sys
temp = sys.stdout
sys.stdout = open('test.txt','w')
print 'hello world'
sys.stdout = temp #恢复默认映射关系
print 'nice'

赋值到自定义对象

class Test:
	def write(self,string):
		#do something you wanna do
test = Test()
temp = sys.stdout
sys.stdout = test
print 'hello world'
posted @ 2021-08-12 10:22  wuyuan2011woaini  阅读(183)  评论(0编辑  收藏  举报