【问题标题】:Python output on file and terminal文件和终端上的 Python 输出
【发布时间】:2014-04-10 15:24:43
【问题描述】:

有时我希望我的程序在终端上写一些东西以便立即检查,并在一个文件上写一些东西供以后使用,所以我写了这样的东西:

print "output"
file.write("output")   #the same output as the previous line

是否有可能使用 python 2.6 或 7 以另一种可能更智能的方式进行操作?

【问题讨论】:

  • 你是在问是否有一个函数可以一次输出到文件和终端?
  • print "output" 更像是file.write("output"+"\n")...print 添加一个尾随换行符。请注意,只是一个细节。

标签: python file terminal output


【解决方案1】:

你可以把它包装成一个函数:

>>> def fprint(output):
...    print output
...    with open("somefile.txt", "a") as f:
...        f.write("{}\n".format(output))

如果这是日志信息,您应该查看logging module。使用日志记录模块,您可以轻松配置和控制日志记录事件的多个目标。

来自logging cookbook的示例:

import logging

# set up logging to file - see previous section for more details
logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
                    datefmt='%m-%d %H:%M',
                    filename='/temp/myapp.log',
                    filemode='w')
# define a Handler which writes INFO messages or higher to the sys.stderr
console = logging.StreamHandler()
console.setLevel(logging.INFO)
# set a format which is simpler for console use
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
# tell the handler to use this format
console.setFormatter(formatter)
# add the handler to the root logger
logging.getLogger('').addHandler(console)

# Now, we can log to the root logger, or any other logger. First the root...
logging.info('Jackdaws love my big sphinx of quartz.'

# Now, define a couple of other loggers which might represent areas in your
# application:

logger1 = logging.getLogger('myapp.area1')
logger2 = logging.getLogger('myapp.area2')

logger1.debug('Quick zephyrs blow, vexing daft Jim.') # Won't print, file only
logger1.info('How quickly daft jumping zebras vex.') # Printed and to file
logger2.warning('Jail zesty vixen who grabbed pay from quack.') # Printed and to file
logger2.error('The five boxing wizards jump quickly.') # Printed and to file.

上面的例子会将所有日志级别为logging.DEBUG 或更高级别的消息写入一个名为/temp/myapp.log 的文件中。级别为logging.INFO 的消息打印到sys.stderr。我强烈建议将此模块用于除简单调试打印之外的任何日志记录目的。

编辑:有错误的例子!

【讨论】:

  • 可能在写入文件时附加'\n'
【解决方案2】:

希望还不算太晚,我走了。这对我有用。

import sys
import logging

class Logger(object):
    def __init__(self, filename):
        self.terminal = sys.stdout
        self.log = open(filename, "a")
    def __getattr__(self, attr):
        return getattr(self.terminal, attr)
    def write(self, message):
        self.log.write(message)     
    def flush(self):
        self.log.flush()

然后,它可以用作

sys.stdout = Logger("file.txt")

【讨论】:

    猜你喜欢
    • 2018-07-01
    • 1970-01-01
    • 2011-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-01
    • 1970-01-01
    • 2017-07-07
    相关资源
    最近更新 更多