python 重定向輸入輸出流 腳本

"""
file-like objects that save standard output text in a string and provide
standard input text from a string; redirect runs a passed-in function
with its output and input streams reset to these file-like class objects;
"""

import sys # get built-in modules

class Output: # simulated output file
def init(self):
self.text = '' # empty string when created
def write(self, string): # add a string of bytes
self.text += string
def writelines(self, lines): # add each line in a list
for line in lines: self.write(line)

class Input: # simulated input file
def init(self, input=''): # default argument
self.text = input # save string when created
def read(self, size=None): # optional argument
if size == None: # read N bytes, or all
res, self.text = self.text, ''
else:
res, self.text = self.text[:size], self.text[size:]
return res
def readline(self):
eoln = self.text.find('\n') # find offset of next eoln
if eoln == -1: # slice off through eoln
res, self.text = self.text, ''
else:
res, self.text = self.text[:eoln+1], self.text[eoln+1:]
return res

def redirect(function, pargs, kargs, input): # redirect stdin/out
savestreams = sys.stdin, sys.stdout # run a function object
sys.stdin = Input(input) # return stdout text
sys.stdout = Output()
try:
result = function(*pargs, **kargs) # run function with args
output = sys.stdout.text
finally:
sys.stdin, sys.stdout = savestreams # restore if exc or not
return (result, output) # return result if no exc

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 這周看了關(guān)于“衡量自我的五個維度”,具體有哪五個我就不一一說了,我就來說一下我自己生活當中的例子吧。 ...
    cakehong閱讀 1,371評論 2 1
  • 今天是什么日子 起床:8:30 就寢:23:48 天氣:晴 紀念日: 叫我起床的不是鬧鐘是夢想 年度目標及關(guān)鍵點:...
    拉薩煜閱讀 162評論 0 1
  • 我這個人很奇怪,從小就不太喜歡嘗試新鮮的事物,不嘗試也就算了,還會有強烈的排斥和否定,現(xiàn)在想來,還真不是一般的偏執(zhí)...
    一念微笑_雨舟閱讀 770評論 0 1
  • Snapseed 組合畫筆(蒙版)的使用&案例 Snapseed相比較其他手機修圖軟件其最強大的地方在于局部處理非...
    狗_叔閱讀 4,060評論 0 3

友情鏈接更多精彩內(nèi)容