python输入输出重定向_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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值