python輸出重定向,原理與各類方法總結

2021-10-04 21:13:39 字數 1566 閱讀 4909

背景:

1.當我們在python中呼叫print obj時,事實上是呼叫了sys.stdout.write(obj + 『\n』)

print 將你需要的內容列印到了控制台,然後加了乙個換行符。

2.當我們用 raw_input('input promption: ') 時,事實上是先把提示資訊輸出,然後捕獲輸入

以下兩組在事實上等價:

print 'hello? ', #comma to stay in the same line

hi=sys.stdin.readline()[:-1] # -1 to discard the '\n' in input stream

3.根據背景介紹,我們可以構造乙個具有write方法的物件,讓他將標準輸出重定向,儲存到別的位置,如下:

import sys

class

__redirection__

:

def __init__

(self)

: self.buff=

'' self.__console__=sys.stdout

def write

(self, output_stream)

: self.buff+=output_stream

def to_console

(self)

: sys.stdout=self.__console__

print self.buff

def to_file

(self, file_path)

: f=

open

(file_path,

'w')

sys.stdout=f

print self.buff

f.close()

def flush

(self)

: self.buff=

''

def reset

(self)

: sys.stdout=self.__console__

if __name__==

"__main__"

: # redirection

r_obj=

__redirection__()

sys.stdout=r_obj

# get output stream

print 'hello'

print 'there'

# redirect to console

r_obj.

to_console()

# redirect to file

r_obj.

to_file

('out.log'

)

# flush buffer

r_obj.

flush()

# reset

r_obj.

reset

()

python輸出重定向

由於考慮到將命令列程式轉成ui程式,原先在命令列中直接輸出的資訊必須輸出到特定介面中,考慮到應該有重定向的功能,baidu了一下,比較簡單,實現 如下,可以先重定向到某個變數,再將其重定向系統並列印出來。usr bin env python coding utf 8 import sys 定義標準輸...

輸入重定向,正確輸出重定向,錯誤輸出重定向

一 標準輸入 stdin a.輸入重定向 標準輸入 作用 將原先鍵盤輸入的內容改由檔案內容代替 root wenwen cat test.txt asdas asdas asdas 按crtl d 退出 將network內容匯入到test.txt中去 root wenwen cat test.txt...

python 如何重定向輸出

在windows和linux終端中,可以用 和 符號將程式輸出重定向到檔案中,那麼在程式內部是否也可以執行相應操作呢?python使用三個io檔案流來管理標準輸入 輸出和錯誤輸出,分別是sys.stdin sys.stdout和sys.stderr 所以,我們要做的僅僅是改變變數的值為目標檔案流,就...