sur*_*ork 59 python printing redirect
我搜索了Google,Stack Overflow和我的Python用户指南,但没有找到一个简单,可行的答案.
我在Windows 7 x64计算机上创建了一个文件c:\ goat.txt,并尝试将"test"打印到该文件.我根据StackOverflow上提供的示例尝试了以下内容:
此时我不想使用日志模块,因为我从文档中无法理解基于二进制条件创建简单日志.打印很简单但是如何重定向输出并不明显.
一个简单明了的例子,我可以进入我的interperter是最有帮助的.
此外,赞赏任何信息网站的建议(不是pydocs).
import sys
print('test', file=open('C:\\goat.txt', 'w')) #fails
print(arg, file=open('fname', 'w')) # above based upon this
print>>destination, arg
print>> C:\\goat.txt, "test" # Fails based upon the above
Run Code Online (Sandbox Code Playgroud)
Eli*_*ght 112
如果您使用的是Python 2.5或更早版本,请打开该文件,然后在重定向中使用该文件对象:
log = open("c:\\goat.txt", "w")
print >>log, "test"
Run Code Online (Sandbox Code Playgroud)
如果您使用的是Python 2.6或2.7,则可以使用print作为函数:
from __future__ import print_function
log = open("c:\\goat.txt", "w")
print("test", file = log)
Run Code Online (Sandbox Code Playgroud)
如果您使用的是Python 3.0或更高版本,则可以省略将来的导入.
如果要全局重定向打印语句,可以设置sys.stdout:
import sys
sys.stdout = open("c:\\goat.txt", "w")
print ("test sys.stdout")
Run Code Online (Sandbox Code Playgroud)
kol*_*bos 48
要重定向所有打印的输出,您可以执行以下操作:
import sys
with open('c:\\goat.txt', 'w') as f:
sys.stdout = f
print "test"
Run Code Online (Sandbox Code Playgroud)
Tri*_*Tao 16
稍微粗略的方式(与上面的答案不同,它们都是有效的)将仅通过控制台将输出定向到文件中.
所以想象你有 main.py
if True:
print "hello world"
else:
print "goodbye world"
Run Code Online (Sandbox Code Playgroud)
你可以做
python main.py >> text.log
Run Code Online (Sandbox Code Playgroud)
然后text.log将获得所有输出.
如果您已经有一堆打印语句并且不想单独更改它们以打印到特定文件,这很方便.只需在上层执行此操作并将所有打印件定向到文件(唯一的缺点是您只能打印到单个目标).
基于以前的答案,我认为这是执行(简单)上下文管理器样式的完美用例:
import sys
class StdoutRedirection:
"""Standard output redirection context manager"""
def __init__(self, path):
self._path = path
def __enter__(self):
sys.stdout = open(self._path, mode="w")
return self
def __exit__(self, exc_type, exc_val, exc_tb):
sys.stdout.close()
sys.stdout = sys.__stdout__
Run Code Online (Sandbox Code Playgroud)
进而:
with StdoutRedirection("path/to/file"):
print("Hello world")
Run Code Online (Sandbox Code Playgroud)
此外,向StdoutRedirection
类添加一些功能也很容易(例如,可以更改路径的方法)