将标准输出重定向到 Python 中的文件? [英] Redirect stdout to a file in Python?

查看:65
本文介绍了将标准输出重定向到 Python 中的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将标准输出重定向到 Python 中的任意文件?

How do I redirect stdout to an arbitrary file in Python?

当一个长时间运行的 Python 脚本(例如 Web 应用程序)从 ssh 会话中启动并在后台运行,并且 ssh 会话关闭时,应用程序将引发 IOError 并在尝试写入标准输出时失败.我需要找到一种方法将应用程序和模块输出到文件而不是标准输出,以防止由于 IOError 导致的失败.目前,我使用 nohup 将输出重定向到一个文件,这样就完成了工作,但出于好奇,我想知道是否有一种方法可以不使用 nohup 来做到这一点.

When a long-running Python script (e.g, web application) is started from within the ssh session and backgounded, and the ssh session is closed, the application will raise IOError and fail the moment it tries to write to stdout. I needed to find a way to make the application and modules output to a file rather than stdout to prevent failure due to IOError. Currently, I employ nohup to redirect output to a file, and that gets the job done, but I was wondering if there was a way to do it without using nohup, out of curiosity.

我已经尝试过 sys.stdout = open('somefile', 'w'),但这似乎并不能阻止某些外部模块仍然输出到终端(或者 sys.stdout = ... 行根本没有触发).我知道它应该可以通过我测试过的更简单的脚本运行,但我还没有时间在网络应用程序上进行测试.

I have already tried sys.stdout = open('somefile', 'w'), but this does not seem to prevent some external modules from still outputting to terminal (or maybe the sys.stdout = ... line did not fire at all). I know it should work from simpler scripts I've tested on, but I also didn't have time yet to test on a web application yet.

推荐答案

如果您想在 Python 脚本中进行重定向,将 sys.stdout 设置为文件对象即可:

If you want to do the redirection within the Python script, setting sys.stdout to a file object does the trick:

import sys
sys.stdout = open('file', 'w')
print('test')
sys.stdout.close()

一种更常见的方法是在执行时使用 shell 重定向(在 Windows 和 Linux 上相同):

A far more common method is to use shell redirection when executing (same on Windows and Linux):

$ python foo.py > file

这篇关于将标准输出重定向到 Python 中的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆