Python,将函数的输出重定向到文件中
我正在尝试将函数的输出存储到Python中的文件中,我正在尝试这样做:Python,将函数的输出重定向到文件中,python,python-3.x,Python,Python 3.x,我正在尝试将函数的输出存储到Python中的文件中,我正在尝试这样做: def test(): print("This is a Test") file=open('Log','a') file.write(test()) file.close() 但当我这样做时,我会得到以下错误: TypeError:参数1必须是字符串或只读字符缓冲区, 不是没有 PD:我正在尝试为一个无法修改的函数执行此操作。解决方案1: import contextlib from contextlib
def test():
print("This is a Test")
file=open('Log','a')
file.write(test())
file.close()
但当我这样做时,我会得到以下错误:
TypeError:参数1必须是字符串或只读字符缓冲区,
不是没有
PD:我正在尝试为一个无法修改的函数执行此操作。解决方案1:
import contextlib
from contextlib import ExitStack
def test():
print('hello world')
with ExitStack() as stack:
f = stack.enter_context(open('Log', 'a'))
stack.enter_context(contextlib.redirect_stdout(f))
test()
print("I'm not logged")
您应该使用日志记录,而不是使用打印:
import logging
logger = logging.getLogger('myapp')
hdlr = logging.FileHandler('/tmp/myapp.log')
logger.addHandler(hdlr)
logger.setLevel(logging.INFO)
def test():
logger.info("This is a Test")
test()
上面的代码工作正常,您可以使用它。
PS:检查文件/tmp/myapp.log中的输出
解决方案2:
import contextlib
from contextlib import ExitStack
def test():
print('hello world')
with ExitStack() as stack:
f = stack.enter_context(open('Log', 'a'))
stack.enter_context(contextlib.redirect_stdout(f))
test()
print("I'm not logged")
只需在命令行中运行代码,并将所有输出存储到“text.log”文件中
python main.py >> text.log
解决方案3:
import contextlib
from contextlib import ExitStack
def test():
print('hello world')
with ExitStack() as stack:
f = stack.enter_context(open('Log', 'a'))
stack.enter_context(contextlib.redirect_stdout(f))
test()
print("I'm not logged")
您需要通过为标准输出分配一个实现
write
方法的对象(如文件)来重定向标准输出
import sys
def test():
print("This is a Test")
stdout_backup = sys.stdout
with open('Log', 'a') as f:
sys.stdout = f
test()
sys.stdout = stdout_backup
每当需要成对执行任何操作时,请使用上下文管理器
在这种情况下,请使用contextlib.redirect\u stdout
:
with open('Log','a') as f:
with contextlib.redirect_stdout(f):
test()
编辑:如果要将其作为字符串,请使用io.StringIO
:
f = io.StringIO()
with contextlib.redirect_stdout(f):
test()
s = f.getvalue()
您可以根据@o11c答案定义装饰器:
def redirect_output_to_file(fname, overwrite=False):
def real_redirect_output_to_file(func):
def wrapper(*args, **kwargs):
import contextlib
with open(fname, 'w' if overwrite else 'a') as f:
with contextlib.redirect_stdout(f):
retval = func(*args, **kwargs)
return retval
return wrapper
return real_redirect_output_to_file
然后将其用于任何功能:
@redirect_output_to_file('test_output.log')
def test():
print('Hi')
函数是否在同一个文件中? 因为这是你可以做的事情 解决方案1:
import sys
def test():
print("This is a test")
out = sys.stdout
with open("Log", "a") as output:
sys.stdout = output
test()
sys.stdout = out
给予
文件中的内容
This is a test
This is a test
问题是函数只打印,但不返回任何内容。添加了Python 3.4,它允许您将标准输出重定向到文件:
解决方案2:
PS C:\Users\tan\Desktop> cat stdout.py
def test():
print("This is a Test")
from contextlib import redirect_stdout
with open('stdout.txt', 'w') as f:
with redirect_stdout(f):
test()
print('stdout in console again')
如果您发布了示例Yes,您希望捕获stdin输出。例如,在我上面发布的内容中,我想将“这是一个测试”存储在一个名为“Log”的文件中。如果有帮助,请检查此答案:Yes,它起作用了。非常感谢。是的,但这需要我修改函数本身,而我无法修改它,该函数会打印出一些我需要存储在文件中的输出。解决方案2适合您吗?这将为我提供整个脚本输出,不仅仅是函数,我只需要函数。回答很好,顺便说一句,为了避免使用嵌套WITH语句,我们可以使用ExitStack@AntoineFontaine问题被标记为python3,并且没有人再使用3.2或3.3了。公平地说,它也被标记为python,并且有很多人仍然在使用Python2.n,不管你的偏好是什么。嗯,Pypi上总是有
contextlib2
模块。。。真的,任何仍在使用Python2的人都应该被用来寻找后台端口。太好了!已搜索此文件一段时间:=