Python中sys.stdout方法的语法示例详解

 更新时间:2023年09月13日 14:57:20   作者:小小程序员ol  
Python中sys 模块中的一个方法是stdout ,它使用其参数直接显示在控制台窗口上,print() 方法,它有相同的行为,首先转换为sys.stdout() 方法,然后在控制台显示结果,本文给大家介绍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 buffer

sys.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') ])
# 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() 方法来存储它。我们将所有的控制台输出存储在同一个日志文件中。

这样,我们可以存储任何打印到控制台的输出,并将其保存到日志文件中。

到此这篇关于Python中sys.stdout方法的文章就介绍到这了,更多相关Python sys.stdout方法内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Celery批量异步调用任务一直等待结果问题

    Celery批量异步调用任务一直等待结果问题

    这篇文章主要介绍了Celery批量异步调用任务一直等待结果问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-11-11
  • Python中sort和sorted函数代码解析

    Python中sort和sorted函数代码解析

    这篇文章主要介绍了Python中sort和sorted函数代码解析,小编觉得还是挺不错的,具有一定借鉴价值,需要的朋友可以参考下
    2018-01-01
  • Django使用Celery异步任务队列的使用

    Django使用Celery异步任务队列的使用

    这篇文章主要介绍了Django使用Celery异步任务队列的使用,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-03-03
  • python中取整数的几种方法

    python中取整数的几种方法

    这篇文章主要给大家分享python中取整数的几种方法技巧,文章将围绕python取整数的详细的相关资料展开内容,需要的朋友可以参考一下,希望对你有所帮助
    2021-11-11
  • Python使用socket模块实现简单tcp通信

    Python使用socket模块实现简单tcp通信

    这篇文章主要介绍了Python使用socket模块实现简单tcp通信,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-08-08
  • python操作XML格式文件的一些常见方法

    python操作XML格式文件的一些常见方法

    最近有同学询问如何利用Python处理xml文件,特此整理一篇比较简洁的操作手册,下面这篇文章主要给大家介绍了关于python操作XML格式文件的一些常见方法,文中通过实例代码介绍的非常详细,需要的朋友可以参考下
    2022-07-07
  • Python与C/C++的相互调用案例

    Python与C/C++的相互调用案例

    这篇文章主要介绍了Python与C/C++的相互调用案例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2021-03-03
  • 将图片文件嵌入到wxpython代码中的实现方法

    将图片文件嵌入到wxpython代码中的实现方法

    前面一篇文章中提到的那个程序,GUI中包含了一张图片。在编译成exe文件发布时,无法直接生成一个单独的exe文件。因此需要直接把图片写入到代码中
    2014-08-08
  • Python数据分析与处理(一)--北京高考分数线统计分析

    Python数据分析与处理(一)--北京高考分数线统计分析

    这篇文章主要介绍了Python数据分析与处理北京高考分数线统计分析,文章问绕Python数据分析与处理相关资料的介绍,展开对北京高考分数线统计分析,需要的小伙伴可以参考一下
    2021-12-12
  • 解决pandas.DataFrame.fillna 填充Nan失败的问题

    解决pandas.DataFrame.fillna 填充Nan失败的问题

    今天小编就为大家分享一篇解决pandas.DataFrame.fillna 填充Nan失败的问题。具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-11-11

最新评论