0
点赞
收藏
分享

微信扫一扫

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

奋斗De奶爸 2022-04-03 阅读 153
python

文档解释:

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()

运行结果如下:

 

举报

相关推荐

0 条评论