做网站需要花费那方面的钱,wordpress外链缩略图,服装与服饰设计,湖南seo优化价格What#xff1f;在 Python 程序中#xff0c;使用 print 输出调试信息的做法非常常见#xff0c;但有的时候我们需要将 print 的内容改写到其他位置#xff0c;比如一个文件中#xff0c;便于随时排查。但是又不希望大面积替换 print 函数#xff0c;这就需要一些技巧实现…What在 Python 程序中使用 print 输出调试信息的做法非常常见但有的时候我们需要将 print 的内容改写到其他位置比如一个文件中便于随时排查。但是又不希望大面积替换 print 函数这就需要一些技巧实现。一种典型的做法是在代码开始的地方增加这样的代码def log_to_file(* args):# write all args to some a filepassprint log_to_file修改 print 方法之后的 print 实际上就不是内置方法了。在 Linux 下也可以通过 shell 的输出重定向将 print 的内容写入文件python3 your_script.py log.txt其实在 Python 代码中也可以通过输出重定向技术直接实现上面的目的。重定向 stdoutstdout 是系统的标准输出通常是 shell 命令行。如果我们用其他对象覆盖 sys.stdout 就可以实现输出的重定向。Python 使用任意实现了 write 方法的对象作为标准输出对象。下面定义了一个 OutputWrapperclass OutputWrapper:def __init__(self, to_file):self._to to_filedef write(self, data):# lets write to log file with some extra string.self._to.write(-----)self._to.write(data)它实现了 write 方法它将输出内容写入 to_file 我们再多做一点工作在每次调用 print 前插入一段 “-----”。下面我们用 OutputWrapper 实例替换原生 sys.stdoutimport sysif __name__ __main__:# the log file namelogname log.txtwith open(logname,a) as logfile:# save original stdoutoriginal sys.stdout# redirect stdoutsys.stdout OutputWrapper(logfile)# outputprint(line 1)print(line 2)# restore stdoutsys.stdout original运行时命令行的输出消失了如果查看 log.txt -----line 1----------line 2-----原来 print 的内容已经写到文件中了此时 log.txt 就相当于命令行输出了。为什么 “line1” 和 “line2” 后面也多了额外输出呢这是因为 print 方法会自动在尾部追加输出一个 ‘\n’又调用了一次 print(’\n’)。How 这种重定向技术是如何实现的其实一切就在最熟悉不过的 print 方法中。print 方法是 Python 的内建函数其原型为print(*objects, sep , end\n, filesys.stdout, flushFalse)第一个参数是不定参数表示 print 的对象sep 是多个输出对象之间的分隔符所以 print(‘a’, ‘b’) 会输出 “a b”这是因为 sep 默认是空格你也可以设置为其他字符串end 是行位字符默认是换行这也是 print 总是一行的原因如果不希望换行可以用参数 end “”;file 非常重要表示 print 方法的输出对象最终的输出工作是通过 file.write 实现的默认情况下 file sys.stdout。flush 与输出缓冲有关暂时不必关心。前面的输出重定向可以总结为这样的流程修改了 sys.stdout -- print 默认 file sys.stdout -- 间接修改了 print 的输出对象。原来如此Built-in Functionsdocs.python.org首发公众号 “江川Go”关注了解程序员的烧脑日常。