In Python, file objects sys.stdin, sys.stdout and sys.stderr are repectively the standard input stream, the standard output stream and standard error stream of interpreter. At program startup, the initial values of these objects are saved by sys.__stdin__, __sys.stdout__ and sys.__stderr__, for restoring standard stream objects during finalization.
1. Console Output Redirection
In console, output redirection using > and >>, and > represents overwriting content, >> represents adding content.
echo print('hello world') > test.py
test.py > test.txt
2. print Redirection
import sys
print('hello', file=sys.stderr)
3. sys.stdout Redirection
Assigning a writable object to sys. stdout can cause subsequent print statements to output to that object. After the redirection is completed, sys.stdout should be restored to its original default value, which is standard output.
import sys
savedStdout = sys.stdout #保存标准输出流
with open('out.txt', 'w+') as file:
sys.stdout = file #标准输出重定向至文件
print('This message is for file!')
sys.stdout = savedStdout #恢复标准输出流
print(This message is for screen!')
from PyQt5.QtWidgets import QApplication, QMainWindow, QPlainTextEdit
import sys
class Edit(QPlainTextEdit):
def __init__(self, parent=None):
super().__init__()
self.setParent(parent)
self.setGeometry(0, 0, 200, 200)
self.appendPlainText('123')
def write(self, s=None): # 必须有write函数的对象才可以赋值给sys.stdout
self.appendPlainText(s)
if __name__ == '__main__':
app = QApplication(sys.argv)
std = sys.stdout
window = QMainWindow()
window.setGeometry(0, 0, 500, 500)
edit = Edit(parent=window)
sys.stdout = edit
window.show()
print('yes')
sys.stdout = std
print('yes')
app.exec_()
4. Logger Redirection
from PyQt5.QtWidgets import QApplication, QMainWindow, QPlainTextEdit
import sys
import logging
class Edit(QPlainTextEdit, logging.Handler):
def __init__(self, parent=None):
super().__init__()
self.setParent(parent)
self.setGeometry(0, 0, 200, 200)
self.appendPlainText('123')
self.setReadOnly(True)
self.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
def emit(self, s=None):
s = self.format(s)
self.appendPlainText(s)
if __name__ == '__main__':
app = QApplication(sys.argv)
window = QMainWindow()
window.setGeometry(0, 0, 500, 500)
edit = Edit(parent=window)
logging.getLogger().addHandler(edit)
logging.getLogger().setLevel(logging.DEBUG)
window.show()
logging.info('\nhello')
app.exec_()
Because print can be used in every Python code and logging is limitted, then the print output redirection is recommanded.