前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python 重定向输入输出流 脚本

python 重定向输入输出流 脚本

作者头像
用户5760343
发布2022-05-13 17:20:28
6210
发布2022-05-13 17:20:28
举报
文章被收录于专栏:sktjsktj

"""

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

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2022-05-13,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档