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

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

相关文章
|
19天前
|
数据采集 存储 搜索推荐
打造个性化网页爬虫:从零开始的Python教程
【8月更文挑战第31天】在数字信息的海洋中,网页爬虫是一艘能够自动搜集网络数据的神奇船只。本文将引导你启航,用Python语言建造属于你自己的网页爬虫。我们将一起探索如何从无到有,一步步构建一个能够抓取、解析并存储网页数据的基础爬虫。文章不仅分享代码,更带你理解背后的逻辑,让你能在遇到问题时自行找到解决方案。无论你是编程新手还是有一定基础的开发者,这篇文章都会为你打开一扇通往数据世界的新窗。
|
3天前
|
机器学习/深度学习 数据采集 算法
数据稀缺条件下的时间序列微分:符号回归(Symbolic Regression)方法介绍与Python示例
有多种方法可以处理时间序列数据中的噪声。本文将介绍一种在我们的研究项目中表现良好的方法,特别适用于时间序列概况中数据点较少的情况。
16 1
数据稀缺条件下的时间序列微分:符号回归(Symbolic Regression)方法介绍与Python示例
|
4天前
|
消息中间件 关系型数据库 数据库
Python实时监测数据库表数据变化的方法
在实现时,需要考虑到应用的实时性需求、数据库性能影响以及网络延迟等因素,选择最适合的方法。每种方法都有其适用场景和限制,理解这些方法的原理和应用,将帮助开发者在实际项目中做出最合适的技术选择。
41 17
|
4天前
|
XML 数据格式 Python
Python技巧:将HTML实体代码转换为文本的方法
在选择方法时,考虑到实际的应用场景和需求是很重要的。通常,使用标准库的 `html`模块就足以满足大多数基本需求。对于复杂的HTML文档处理,则可能需要 `BeautifulSoup`。而在特殊场合,或者为了最大限度的控制和定制化,可以考虑正则表达式。
21 12
|
2天前
|
Python
全网最适合入门的面向对象编程教程:Python函数方法与接口-函数与方法的区别和lamda匿名函数
【9月更文挑战第15天】在 Python 中,函数与方法有所区别:函数是独立的代码块,可通过函数名直接调用,不依赖特定类或对象;方法则是与类或对象关联的函数,通常在类内部定义并通过对象调用。Lambda 函数是一种简洁的匿名函数定义方式,常用于简单的操作或作为其他函数的参数。根据需求,可选择使用函数、方法或 lambda 函数来实现代码逻辑。
|
11天前
|
Python
Python中几种lambda排序方法
【9月更文挑战第7天】在Python中,`lambda`表达式常用于配合排序函数,实现灵活的数据排序。对于基本列表,可以直接使用`sorted()`进行升序或降序排序;处理复杂对象如字典列表时,通过`lambda`指定键值进行排序;同样地,`lambda`也适用于根据元组的不同位置元素来进行排序。
|
14天前
|
缓存 测试技术 Apache
告别卡顿!Python性能测试实战教程,JMeter&Locust带你秒懂性能优化💡
【9月更文挑战第5天】性能测试是确保应用在高负载下稳定运行的关键。本文介绍Apache JMeter和Locust两款常用性能测试工具,帮助识别并解决性能瓶颈。JMeter适用于测试静态和动态资源,而Locust则通过Python脚本模拟HTTP请求。文章详细讲解了安装、配置及使用方法,并提供了实战案例,帮助你掌握性能测试技巧,提升应用性能。通过分析测试结果、模拟并发、检查资源使用情况及代码优化,确保应用在高并发环境下表现优异。
42 5
|
21天前
|
Python
|
2天前
|
存储 数据挖掘 测试技术
Python接口自动化中操作Excel文件的技术方法
通过上述方法和库,Python接口自动化中的Excel操作变得既简单又高效,有助于提升自动化测试的整体质量和效率。
8 0
|
2天前
|
数据处理 开发者 Python
探索Python中的列表推导式在Python编程中,列表推导式是一种简洁而高效的方法,用于从现有的列表创建新列表。本文将深入探讨列表推导式的用法、优势以及一些实际应用示例。
列表推导式是Python提供的一种强大工具,它允许开发者以更简洁的语法快速生成列表。通过结合循环和条件语句,列表推导式能够简化代码结构,提高开发效率。本文详细介绍了列表推导式的基本用法,并通过实例展示了其在数据处理、转换和过滤中的广泛应用。
9 0