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

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

相关文章
|
1天前
|
机器学习/深度学习 数据可视化 前端开发
【Python机器学习专栏】机器学习模型评估的实用方法
【4月更文挑战第30天】本文介绍了机器学习模型评估的关键方法,包括评估指标(如准确率、精确率、召回率、F1分数、MSE、RMSE、MAE及ROC曲线)和交叉验证技术(如K折交叉验证、留一交叉验证、自助法)。混淆矩阵提供了一种可视化分类模型性能的方式,而Python的scikit-learn库则方便实现这些评估。选择适合的指标和验证方法能有效优化模型性能。
|
1天前
|
机器学习/深度学习 算法 Python
【Python机器学习专栏】Python中的特征选择方法
【4月更文挑战第30天】本文介绍了机器学习中特征选择的重要性,包括提高模型性能、减少计算成本和增强可解释性。特征选择方法主要包括过滤法(如相关系数、卡方检验和互信息)、包装法(如递归特征消除和顺序特征选择)和嵌入法(如L1正则化和决策树)。在Python中,可利用`sklearn`库的`feature_selection`模块实现这些方法。通过有效的特征选择,能构建更优的模型并深入理解数据。
|
1天前
|
机器学习/深度学习 数据采集 数据可视化
【Python 机器学习专栏】数据缺失值处理与插补方法
【4月更文挑战第30天】本文探讨了Python中处理数据缺失值的方法。缺失值影响数据分析和模型训练,可能导致模型偏差、准确性降低和干扰分析。检测缺失值可使用Pandas的`isnull()`和`notnull()`,或通过可视化。处理方法包括删除含缺失值的行/列及填充:固定值、均值/中位数、众数或最近邻。Scikit-learn提供了SimpleImputer和IterativeImputer类进行插补。选择方法要考虑数据特点、缺失值比例和模型需求。注意过度插补和验证评估。处理缺失值是提升数据质量和模型准确性关键步骤。
|
2天前
|
API 数据库 Python
Python web框架fastapi数据库操作ORM(二)增删改查逻辑实现方法
Python web框架fastapi数据库操作ORM(二)增删改查逻辑实现方法
|
2天前
|
Linux Python Windows
Python更换国内pip源详细教程
Python更换国内pip源详细教程
|
2天前
|
Linux Python Windows
Python虚拟环境virtualenv安装保姆级教程(Windows和linux)
Python虚拟环境virtualenv安装保姆级教程(Windows和linux)
|
2天前
|
机器学习/深度学习 数据可视化 数据挖掘
实用技巧:提高 Python 编程效率的五个方法
本文介绍了五个提高 Python 编程效率的实用技巧,包括使用虚拟环境管理依赖、掌握列表推导式、使用生成器提升性能、利用装饰器简化代码结构以及使用 Jupyter Notebook 进行交互式开发。通过掌握这些技巧,可以让你的 Python 编程更加高效。
|
2天前
|
数据可视化 数据处理 Python
Python有很多创建图表的常用方法
Python的图表创建工具有多种,如基础的Matplotlib用于绘制各类图表,包括线图和柱状图等;Seaborn是Matplotlib的扩展,擅长复杂可视化如热力图和回归图;Plotly和Bokeh提供交互式图表,适合高维数据展示,支持散点图、线图等;Pandas虽主要是数据处理库,但也具备基本绘图功能;Pygal专注于生成可缩放矢量图,如线图和饼图,支持SVG输出;而Altair基于Vega,适用于交互式和高维数据的可视化。选择哪种库取决于具体需求和图表类型。
12 2
|
7天前
|
运维 Shell Python
Shell和Python学习教程总结
Shell和Python学习教程总结
|
7天前
|
运维 Shell Python
Shell和Python学习教程总结
Shell和Python学习教程总结