
166.jpg
概述
當(dāng)我們在Python的print打印時(shí),我們到底在使用什么? 其實(shí)print語句不過是Python簡便使用的特性體驗(yàn)而已,其背后就是sys.stdout對象的簡單接口,即我們也可以利用sys.stdout完成所有print打印行為,比如打印Hello, world!。
import sys
sys.stdout.write('Hello, world!')
示例結(jié)果:
Hello, world!
再者
import sys
s1 = 'Hello,'
s2 = 'world!'
print(s1, s2, end='\n')
sys.stdout.write(str(s1) + ' ' + str(s2) + '\n')
示例結(jié)果:
Hello, world!
Hello, world!
重定向輸出流
我們已經(jīng)知道print對sys.stdout的依賴,那么我們能否將sys.stdout賦值為標(biāo)準(zhǔn)輸出流以外的東西,即將print的文字傳送到其他地方。
import sys
s1 = 'Hello,'
s2 = 'world!'
sys.stdout = open('hello.txt', 'a')
...
print(s1, s2)
print(s2, s1)
hello.text內(nèi)容:
Hello, world!
world! Hello,
可以看到標(biāo)準(zhǔn)輸出流并沒有打印任何信息,而需要被打印的內(nèi)容全部被寫入hello.txt文件中,這是為何? 因?yàn)槲覀儼?code>sys.stdout重設(shè)成已經(jīng)打開的文件對象,重設(shè)之后,程序中所有的print都會將文字輸出至文件hello.txt中,即進(jìn)程中只有一個sys模塊,通過這種方式就可以將所有的print進(jìn)行重定向。當(dāng)然我們也可以對單個print進(jìn)行重定向,即上節(jié)介紹的print函數(shù)中的file參數(shù)完成重定向,這也是為何print定義file之后不會進(jìn)行原始輸出流的操作,即屏幕沒有打印該次print函數(shù)的字符串信息。