加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

Python输出文件和终端

发布时间:2020-12-20 12:06:05 所属栏目:Python 来源:网络整理
导读:有时我希望我的程序在终端上写一些东西以便立即检查,并在一个文件上供以后使用,所以我写了类似的东西: print "output"file.write("output") #the same output as the previous line 有可能,使用python 2.6或7,以另一种方式,也许更聪明的方式做到这一点? 解
有时我希望我的程序在终端上写一些东西以便立即检查,并在一个文件上供以后使用,所以我写了类似的东西:

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

有可能,使用python 2.6或7,以另一种方式,也许更聪明的方式做到这一点?

解决方法

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

>>> 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的文件中.具有level logging.INFO的消息将打印到sys.stderr.我强烈建议将此模块用于上述简单调试打印的任何日志记录.

编辑:有错误的例子!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读