1.print

def print(self, *args, sep=' ', end='\n', file=None): # known special case of print
    print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file:  a file-like object (stream); defaults to the current sys.stdout.
    sep:   string inserted between values, default a space.
    end:   string appended after the last value, default a newline.
    flush: whether to forcibly flush the stream.

阅读上面的源代码,print的file对象指向sys.stdout,即标准输出流,打印输出到控制台;

可以直接给file对象赋值,使其指向文件对象,打印输出到文件;

print("123", file=open("text1.log", "w"))
 

text1.log文件已经写入123

2.sys.stdout重定向

sys.stdout是python中的标准输出流,默认是映射到控制台的,即将信息打印到控制台。

在python中调用print时,默认情况下,实际上是调用了sys.stdout.write(obj+"\n")

print("hello")
sys.stdout.write("hello\n")
 

控制台输出
hello
hello

3.sys.stdout重定向到文件对象

sys.stdout默认是映射到控制台,可以通过修改映射关系把打印操作重定向到其他地方,例如:可以将文件对象引用赋给sys.stdout,实现sys.stdout的重定向。

# 保存原始sys.stdout进行备份
save_stdout = sys.stdout
# sys.stdout重定向,指向文件对象
sys.stdout = open("test.txt", "w")
# print调用sys.stdout的write方法(此时sys.stdout指向文件对象,实际上调用的就是文件对象的write方法),打印到test.txt文件
print("hello world")
# 恢复,标准输出流
sys.stdout = save_stdout
# print调用sys.stdout的write方法,标准输出流默认打印到控制台
print("hello world again")
 

test.txt文件已经写入hello world

控制台输出
hello world again

上面代码可以理解为:

4.sys.stdout重定向到自定义对象

sys.stdout可以重定向到一个实现write方法的自定义对象,从上面的例子中知道,print方法调用的实际是sys.stdout.write方法,所以自定义对象一定要实现write方法。

import sys
import tkinter
import tkinter.scrolledtext
class RedictStdout:
    def __init__(self, scroll_text):
        # 保存原始sys.stdout进行备份
        self.save_stdout = sys.stdout
        # sys.stdout重定向,指向该对象
        sys.stdout = self
        self.scroll_text = scroll_text
    def write(self, message):
        # message即sys.stdout接收到的输出信息
        self.scroll_text.insert(tkinter.END, message)  # 在多行文本控件最后一行插入message
        # self.scroll_text.update()  # 更新显示的文本
        self.scroll_text.see(tkinter.END)  # 始终显示最后一行,不加这句,当文本溢出控件最后一行时,可能不会自动显示最后一行
    def restore(self):
    	# 恢复标准输出流
        sys.stdout = self.save_stdout
def click():
    print("hello word")
window = tkinter.Tk()
scroll_text = tkinter.scrolledtext.ScrolledText(window, bg="pink")
scroll_text.pack()
button = tkinter.Button(window, text="点击", command=click)
button.pack()
# 实例化对象
rs = RedictStdout(scroll_text)
# print调用sys.stdout的write方法,sys.stdout指向rs对象,实际上print调用rs的write方法
# rs的write方法,实现了scrolltext组件插入sys.stdout收到的message信息,即print要打印的信息
window.mainloop()
# 恢复标准输出流
rs.restore()

上面代码可以理解为:
在这里插入图片描述
5.logging模块日志输出

logging的基本用法:

# 设置日志等级为DEBUG
logging.basicConfig(level=logging.DEBUG)
logging.error("logging error message")
 

控制台输出
ERROR:root:logging error message

阅读logging模块源代码,发现basicConfig默认创建一个StreamHandler,并且其指向标准错误输出流,即sys.stderr,默认情况下日志输出到控制台。

def basicConfig(**kwargs):
    Do basic configuration for the logging system.
    This function does nothing if the root logger already has handlers
    configured, unless the keyword argument *force* is set to ``True``.
    It is a convenience method intended for use by simple scripts
    to do one-shot configuration of the logging package.
    The default behaviour is to create a StreamHandler which writes to
    sys.stderr, set a formatter using the BASIC_FORMAT format string, and
    add the handler to the root logger.
    A number of optional keyword arguments may be specified, which can alter
    the default behaviour.
    ...
class StreamHandler(Handler):
    A handler class which writes logging records, appropriately formatted,
    to a stream. Note that this class does not close the stream, as
    sys.stdout or sys.stderr may be used.
    terminator = '\n'
    def __init__(self, stream=None):
        Initialize the handler.
        If stream is not specified, sys.stderr is used.
        Handler.__init__(self)
        if stream is None:
            stream = sys.stderr
        self.stream = stream

所以,在4点中直接使用logging的基本用法,是无法让scrolltext显示logging要打印的日志信息的,因为,4点中的代码只做了对sys.stdout的重定向,我们应该加一步对sys.stderr的重定向。

import logging
import sys
import tkinter
import tkinter.scrolledtext
class RedictStdout:
    def __init__(self, scroll_text):
        # 保存原始sys.stdout/sys.stderr进行备份
        self.save_stdout = sys.stdout
        self.save_stderr = sys.stderr
        # sys.stdout/sys.stderr重定向,指向该对象
        sys.stdout = self
        sys.stderr = self
        self.scroll_text = scroll_text
    def write(self, message):
        # message即sys.stdout/sys.stderr接收到的输出信息
        self.scroll_text.insert(tkinter.END, message)  # 在多行文本控件最后一行插入message
        # self.scroll_text.update()  # 更新显示的文本
        self.scroll_text.see(tkinter.END)  # 始终显示最后一行,不加这句,当文本溢出控件最后一行时,可能不会自动显示最后一行
    def restore(self):
    	# 恢复标准输出流
        sys.stdout = self.save_stdout
        sys.stderr = self.save_stderr
def click():
    print("hello word")
    logging.error("logging error message")
window = tkinter.Tk()
scroll_text = tkinter.scrolledtext.ScrolledText(window, bg="pink")
scroll_text.pack()
button = tkinter.Button(window, text="点击", command=click)
button.pack()
# 实例化对象
rs = RedictStdout(scroll_text)
# print调用sys.stdout的write方法,sys.stdout指向rs对象,实际上print调用rs的write方法
# rs的write方法,实现了scrolltext组件插入sys.stdout收到的message信息,即print要打印的信息
# 设置日志等级为DEBUG
logging.basicConfig(level=logging.DEBUG)
# logging.error调用了sys.stderr的write方法,sys.stderr指向rs对象,实际上logging.error调用rs的write方法
# rs的write方法,实现了scrolltext组件插入sys.stderr收到的message信息,即logging.error要打印的信息
window.mainloop()
# 恢复标准输出流
rs.restore()

效果:
在这里插入图片描述
上面代码可以理解为:
在这里插入图片描述

1.printdef print(self, *args, sep=' ', end='\n', file=None): # known special case of print """ print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False) Prints the values to a stream, or to sys.stdout by default. Optional key
print与sys.stdoutpython中,print语句实现打印,从技术角度来说,这是把一个或多个对象转换为其文本表达式形式,然后发送给标准输出流或者类似的文件流,更详细的说,打印与文件和流的概念紧密相连。 我们都知道在python中,向一个文件写东西是通过类似file.write(str)方法实现的,而你可能没想到print语句执行的操作其实也是一个写操作,不过他把我们从外设输入的...
old=sys.stdout #将当前系统输出储存到临时变量 sys.stdout=f #输出重定向到文件 print 'Hello World!' #测试一个打印输出 sys.stdout=old #还原系统输出 f.close() print open('a.txt','r') # 错误的方法,仅用于查看输出,了解python print open
sys.stdout的形式就是print的一种默认输出格式,等于print "%VALUE%" print函数是对sys.stdout的高级封装,看下print函数的解释 Prints the values to a stream, or to sys.stdout by default. Optional keyword arguments: file: a file...
当我们在 Python 中打印对象调用 print(obj) 时候,事实上是调用了 sys.stdout.write(obj+'\n') print 将你需要的内容打印到了控制台,然后追加了一个换行符 print 会调用 sys.stdout 的 write 方法 以下两行在事实上等价: sys.stdout.write('hello'+'\n') print('hello') import sys temp = sys.stdout f = open('test.txt'.
今天在爱奇艺的笔试题里第一次看到sys.stdout.write,之前一直用的是print,因为print()真的简单好用啊。 stdout只能输出字符串,如果要输出数字,也需要先转成字符串形式的;print可以直接输出各种类型 stdout输出结果后不自动换行;print会自动换行 在shell中,stdout输出结果后面会多一项字符串的长度(不知道如何去掉,头疼),而在spyder和py...
It looks like you need to flush stdout periodically (e.g. sys.stdout.flush()). In my testing Python doesn't automatically do this even with print until the program exits. You can run Python with the -u flag to avoid output buffering 解决办法之一:加-u nohup python -u Bilstm-My-Exp-Char.py --train sys.stdout.write(string)   Write string to stream.   Returns the number of characters written (which is always equal to the length of the string). print(value...
标准输出(stdout)指的就是在命令行里,每次你输入指令后,终端上打印出来的那些话,那些反馈。标准错误(stderr)跟标准输出差不多,只不过是程序出错时反馈的内容。标准输入(stdin)就是程序指示让你输入用户名密码之类的这种,这里不多谈输入。 问题是,我们很常用的会让一些脚本自己在后台24/7运行,这种时候脚本的输出内容到屏幕上(标准输出)也没什么意义,我们看不到也保存不了。所以最好让它把...
写得赞,博主用心了。 此国产日志 https://github.com/ydf0509/nb_log 使用原生 loggng封装,兼容性和替换性100%。 1、日志能根据级别能够自动变彩色。 2、print自动变彩色。 3、日志和print在pycahrm控制台的输出都自动可以点击跳转到文件和行号。4、多进程日志切割安全,文件日志写入性能高 5、入参简单,能一键自动记录到多种地方. 相比 loguru 有10胜。 pip install nb_log 。