首页 > 编程语言 >Python教程:sys.stdout方法

Python教程:sys.stdout方法

时间:2023-09-09 17:12:22浏览次数:34  
标签:write stdout Python sys print line my

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

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

标签:write,stdout,Python,sys,print,line,my
From: https://www.cnblogs.com/python1111/p/17689766.html

相关文章

  • Python中跨越多个文件使用全局变量
    这个琐碎的指南是关于在Python中跨多个文件使用全局变量。但是在进入主题之前,让我们简单地看看全局变量和它们在多个文件中的用途。Python中的全局变量全局变量是不属于函数范围的变量,可以在整个程序中使用。这表明全局变量也可以在函数体内部或外部使用。让我们看一个例子:......
  • 初识python--python中的字符串
    python中的字符串1、字符串的定义与访问字符串的定义字符串是一种常见的数据类型=>数据容器的一种,一个变量中可以同时保存多个字符基本语法:使用双引号(三引号的形式支持字符串的换行)变量名称='字符串'变量名称="字符串"#三引号变量名称=''' 锄禾日当午, 汗滴......
  • 初识python--python的列表与元组
    python中的列表与元组一、列表的定义与访问1、为什么需要列表列表是数据容器中的一种,允许我们在列表容器中同时保存多个数据元素如:保存一个学生的名字,可以name='Tom'但是如果要保存100位学生的名字呢2、列表的定义与访问#names=[元素1,元素2,元素3]其中的元素可以是任......
  • 初识python--python的选择分支结构
    python选择结构语句一、if选择结构1、ifelse结构在日常业务中,经常需要进行多条件判断,为了这种场景,引入多分支结构age=int(input('请输入你的年龄:'))ifage<18:print(f"年龄{age},未到18岁,不可使用童工!")elifage>=18&age<=60:print('年龄为%d,合法年龄......
  • 【Python】Python语言基础2
    条件语句if条件1:语句块1elif条件2:语句块2elif条件3:语句块3.....else:语句块4在书写过程中,不要忘记缩进四格!关系运算符>>=<<===!=in前六个多针对于数学关系,最后一个多用于字符串类型赋值的拓展x=x+6这样的代码为累加,也可以写作x+=6,其......
  • python开发之个人微信机器人的二次开发
    简要描述:添加标签请求URL:http://域名地址/addContactLabel请求方式:POST请求头Headers:Content-Type:application/jsonAuthorization:login接口返回参数:参数名必选类型说明wId是String登录实例标识labelName是String标签名称请求参数示例{......
  • python开发之个微的二次开发
    简要描述:添加标签请求URL:http://域名地址/addContactLabel请求方式:POST请求头Headers:Content-Type:application/jsonAuthorization:login接口返回参数:参数名必选类型说明wId是String登录实例标识labelName是String标签名称请求参数示例{"wId":"349be9b5-8734-45ce-811d-4e10ca56......
  • Python基础学习day07
    昨日内容回顾基本数据类型列表(list)1.能够存储多个数据,且可获取单个或整体数据2.中括号括起来[],里面可以存放多个且不同数据类型的数据(包括列表),各个数据用逗号隔开3.索引取值:#索引通常是从0开始L1=[11,12,13,[14,15,16],17]print(L1[3])#出来的结果是14,15,16字典(dict)1.能......
  • Python中列表list常用方法总结
     在Python中,列表(List)是一种有序的数据集合,可以存储任意类型的数据,例如整数、浮点数、字符串、元组、列表等。因为列表是有序的,所以可以通过下标(索引)来访问和修改列表中的元素。Python中的列表是可变的,也就是说可以动态增加和删除元素。创建列表的方法有多种,其中最常见的是使......
  • 31个必备的Python字符串方法总结
     字符串是Python中基本的数据类型,几乎在每个Python程序中都会使用到它。 1、Slicingslicing切片,按照一定条件从列表或者元组中取出部分元素(比如特定范围、索引、分割值)s='hello's=s[:]print(s)#hellos='hello's=s[3:8]print(s)#hello 2......