寒夜星空 发表于 2023-9-9 18:35:01

Python教程:sys.stdout方法

Python中sys 模块中的一个方法是stdout ,它使用其参数直接显示在控制台窗口上。
这些种类的输出可以是不同的,像一个简单的打印语句,一个表达式,或者一个输入提示。print() 方法,它有相同的行为,首先转换为sys.stdout() 方法,然后在控制台显示结果。
sys.stdout 方法的语法

sys.stdout参数
不涉及任何参数。我们使用sys.stdout 作为输出文件对象。
返回值
该方法不返回任何值,只在控制台直接显示输出。
示例:在Python中使用sys.stdout 方法

# import the sys module to use methods
import sys
sys.stdout.write('This is my first line')
sys.stdout.write('This is my second line')输出:
This is my first line This is my second line它将返回sys.stdout.write() 方法中传递的参数并在屏幕上显示。
示例:sys.stdout.write() 与print() 方法

import sys
# print shows new line at the end
print("First line ")
print("Second line ")
# displays output directly on console without space or newline
sys.stdout.write('This is my first line ')
sys.stdout.write('This is my second line ')
# for inserting new line
sys.stdout.write("n")
sys.stdout.write('In new line ')
# writing string values to file.txt
print('Hello', 'World', 2+3, file=open('file.txt', 'w'))输出:
First line
Second line
This is my first line This is my second line
In new line
# file.txt will be created with text "Hello World 5" as a string我们使用sys.stdout.write() 方法直接在控制台显示内容,print() 语句有一个薄薄的stdout() 方法的包装,也是对输入的格式化。所以,默认情况下,它在参数之间留有空格,并输入一个新行。
在Python 3.0版本之后,print() 方法不仅接受stdout() 方法,还接受一个文件参数。为了给出一个行的空格,我们把"n" 传给stdout.write() 方法。
示例代码:使用sys.stdout.write() 方法来显示一个列表
import sys
# sys.stdout assigned to "carry" variable
carry = sys.stdout
my_array = ['one', 'two', 'three']
# printing list items here
for index in my_array:
    carry.write(index)输出:
# prints a list on a single line without spaces
onetwothree输出显示,stdout.write() 方法没有给所提供的参数提供空间或新行。
示例:在Python中使用sys.stdout.flush() 方法

import sys
# import for the use of the sleep() method
import time
# wait for 5 seconds and suddenly shows all output
for index in range(5):
    print(index, end =' ')
    time.sleep(1)
print()
# print one number per second till 5 seconds
for index in range(5):
    # end variable holds /n by default
    print(index, end =' ')
    sys.stdout.flush()
    time.sleep(1)输出结果:
0 1 2 3 4 # no buffer
0 1 2 3 4 # use buffersys.stdout.flush() 方法刷新了缓冲区。这意味着它将把缓冲区的东西写到控制台,即使它在写之前会等待。
示例:在Python中使用sys.stdout.encoding() 方法

# import sys module for stdout methods
import sys
# if the received value is not None, then the function prints repr(receivedValue) to sys.stdout
def display(receivedValue):
    if receivedValue is None:
      return
    mytext = repr(receivedValue)
    # exception handling
    try:
      sys.stdout.write(mytext)
    # handles two exceptions here
    except UnicodeEncodeError:
      bytes = mytext.encode(sys.stdout.encoding, 'backslashreplace')
      if hasattr(sys.stdout, 'buffer'):
            sys.stdout.buffer.write(bytes)
      else:
            mytext = bytes.decode(sys.stdout.encoding, 'strict')
            sys.stdout.write(mytext)
    sys.stdout.write("n")
display("my name")输出:
'my name'方法sys.stdout.encoding() 用于改变sys.stdout 的编码。在方法display() 中,我们用它来评估一个在交互式 Python 会话中插入的表达式。
有一个异常处理程序有两个选项:如果参数值是可编码的,那么就用backslashreplace 错误处理程序进行编码。否则,如果它不是可编码的,应该用sys.std.errors 错误处理程序进行编码。
示例:重复的sys.stdout 到一个日志文件

import sys
# method for multiple log saving in txt file
class multipleSave(object):
    def __getattr__(self, attr, *arguments):
      return self._wrap(attr, *arguments)
    def __init__(self, myfiles):
      self._myfiles = myfiles
    def _wrap(self, attr, *arguments):
      def g(*a, **kw):
            for f in self._myfiles:
                res = getattr(f, attr, *arguments)(*a, **kw)
            return res
      return g
sys.stdout = multipleSave([ sys.stdout, open('file.txt', 'w') ])
# Python小白学习交流群:711312441
# all print statement works here
print ('123')
print (sys.stdout, 'this is second line')
sys.stdout.write('this is third linen')输出:
# file.txt will be created on the same directory with multiple logs in it.
123
<__main__.multipleSave object at 0x00000226811A0048> this is second line
this is third line为了将输出的控制台结果存储在一个文件中,我们可以使用open() 方法来存储它。我们将所有的控制台输出存储在同一个日志文件中。
这样,我们可以存储任何打印到控制台的输出,并将其保存到日志文件中。

来源:https://www.cnblogs.com/python1111/p/17689766.html
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!
页: [1]
查看完整版本: Python教程:sys.stdout方法