python 中的 sys.stdin ,sys.stdout 和sys.stderr

文档解释:

File objects used by the interpreter for standard input, output and errors:

  • stdin is used for all interactive input (including calls to input());

  • stdout is used for the output of print() and expression statements and for the prompts of input();

  • The interpreter’s own prompts and its error messages go to stderr.

1.sys.stdin

sys.stdin是一个标准化输入的方法

 input 等价于sys.stdin.readline()

import sys

print('Enter your name: ')
name = sys.stdin.readline()
print('Hello ',name)

nickname = input("enter your name: ")
print('Hello',nickname + '\n')
sys.stdin.readline()可以实现标准输入,其中默认输入的格式是字符串,如果是int,float类型则需要强制转换。
try:
    while 1:
        print('please input a number: ')
        n = int(sys.stdin.readline().strip('\n'))
        print('please input some numbers: ')  # 若是多输入,strip()默认是以空格分割,返回一个包含多个字符串的list
        sn = sys.stdin.readline().strip()
        if sn == '':
            break
        sn = list(map(int,sn.split())) # 将列表元素转化成int类型
        print(n)
        print(sn,'\n')
except:
    pass

拓展:map(function,iterable,…)

map() 会根据提供的函数对指定序列做映射。

def square(x):
    return x ** 2

ret = map(square, [1, 2, 3, 4, 5])
print(list(ret))# [1, 4, 9, 16, 25]

2.sys.stdout 

stdout用于print和状态表达式的结果输出,及input()的瞬时输出

2.1 python的print 等价于sys.stdout.write()

import os

sys.stdout.write("hello world" + "\n")
print("hello world")

2.2 sys.stdout 重定向

import  os
import sys
temp = sys.stdout
f = open('test.txt','w')
print('heyyy')  # 打印到终端

# 之后使用print函数,都将内容打印到test.txt 文件中
sys.stdout = f 
print('hello')  # 打印到文件中

# 恢复print函数打印到终端上
sys.stdout = temp
print('恢复')  # 打印到终端
f.close()

3.sys.stderr

stderr与stdout一样,用于重定向错误信息至某个文件。

import sys
import traceback
__stderr__ = sys.stderr
sys.stderr = open('errorlog_abc.txt','a')


# 使用traceback 函数定位错误信息
try:
    1/0
except:
    traceback.print_exc()

运行结果如下:

python 中的 sys.stdin ,sys.stdout 和sys.stderr

 

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
青葱年少的头像青葱年少普通用户
上一篇 2023年3月11日
下一篇 2023年3月11日

相关推荐