相关疑难解决方法(0)

记录器配置以记录到文件并打印到stdout

我正在使用Python的日志记录模块将一些调试字符串记录到一个非常好的文件中.现在另外,我想使用这个模块也将字符串打印到stdout.我该怎么做呢?为了将我的字符串记录到文件,我使用以下代码:

import logging
import logging.handlers
logger = logging.getLogger("")
logger.setLevel(logging.DEBUG)
handler = logging.handlers.RotatingFileHandler(
    LOGFILE, maxBytes=(1048576*5), backupCount=7
)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
handler.setFormatter(formatter)
logger.addHandler(handler)
Run Code Online (Sandbox Code Playgroud)

然后调用一个记录器函数

logger.debug("I am written to the file")
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助!

python logging stdout file

310
推荐指数
7
解决办法
21万
查看次数

控制台和文件上的 Python 输出

我正在编写一个代码来分析 PDF 文件。我想在控制台上显示输出,并在文件中保存输出的副本,我使用以下代码将输出保存在文件中:

import sys
sys.stdout = open('C:\\users\\Suleiman JK\\Desktop\\file.txt',"w")
print "test"
Run Code Online (Sandbox Code Playgroud)

但是我是否也可以将输出显示到控制台,但不使用类,因为我不擅长它们?

python console file output

8
推荐指数
3
解决办法
1万
查看次数

sys.stdout没有重新分配给sys .__ stdout__

我是Python的新手,所以我还在学习语言.我遇到的一件事是重新分配sys.stdout来更改print的默认输出.所以我把它写成了一个测试:

import sys
sys.stdout = open('log.txt','a')
print('hey')
sys.stdout.close()
sys.stdout = sys.__stdout__
print('hi')
Run Code Online (Sandbox Code Playgroud)

'嘿'被写入文件,但'hi'无处可见.但是,这可以按预期工作,并且'hey'被写入文件,'hi'被打印到控制台输出:

import sys
sys.__stdout__ = sys.stdout
sys.stdout = open(r'C:\Users\Vincent\Documents\Python\log.txt','a')
print('hey')
sys.stdout.close()
sys.stdout = sys.__stdout__
print('hi')
Run Code Online (Sandbox Code Playgroud)

简而言之,这是一个并不重要的小问题,我只是想知道是否有一个明显的原因导致它不按预期的方式工作.我在Windows 7家庭高级版上使用IDLE和pyscripter在v3.2.3和我的便携式python v3.2.1上尝试过这个.

python python-3.x

7
推荐指数
2
解决办法
2530
查看次数

标签 统计

python ×3

file ×2

console ×1

logging ×1

output ×1

python-3.x ×1

stdout ×1