Python输入流输出流重定向

  1. sys.stdout与print:
    在python中调用print时,事实上调用了sys.stdout.write(obj+’\n’)
    print 将需要的内容打印到控制台,然后追加一个换行符

  2. sys.stdin与input
    sys.stdin.readline( )会将标准输入全部获取,包括末尾的’\n’,因此用len计算长度时是把换行符’\n’算进去了的,但是input( )获取输入时返回的结果是不包含末尾的换行符’\n’的。
    因此如果在平时使用sys.stdin.readline( )获取输入的话,不要忘了去掉末尾的换行符,可以用strip( )函数(sys.stdin.readline( ).strip(’\n’))或sys.stdin.readline( )[:-1]这两种方法去掉换行。

  3. 原始的sys.stdout指向控制台,如果把文件的对象引用赋给sys.stdout,那么print调用的就是文件对象的write方法。
    Windows命令提示符(cmd.exe)和Linux Shell(bash等)均通过">“或”>>“将输出重定向。其中,”>“表示覆盖内容,”>>“表示追加内容。类似地,通过”<“或”<<"将输入重定向

  4. stdin结束输入:

    Windows Ctrl+Z 或者 Ctrl+D
    Linux Ctrl+D
    相当于EOF
    当重定位到文件输入时遇到文件尾自动结束输入

  5. 输入输出重定向在控制台的重定向
    例如给输入输出赋值一个文件对象,就可以很好的将输入输出指向文件
    默认输入输出指向的是控制台
    如需切换回控制台时,赋值回原来的对象就可以

import sys


sys.stdout.write('uhuafufh' + '\t')
sys.stdout.write('sahffhsi' + '\n')
sys.stdout.write('ushsdhuhu' + '\n')

print('-------------------------------------------')

oneLine = sys.stdin.readline()
print(oneLine)
print(len(oneLine))

oneLine = oneLine.strip('\n')
print(oneLine)
print(len(oneLine))
print('-------------------------------------------')

text = sys.stdin.readlines()		# 按Ctrl+D结束输入

print(text)
list1 = []
for line in text:
    line1 = line.strip('\n')     		# 去掉每行末尾的回车符
    list1.append(line1)

print(list1)
print('-------------------------------------------')

‘’‘
按下ctrl+D之后不能再次使用sys.stdin.readline()和sys.stdin.readlines()
 text2 = sys.stdin.readlines()
 print(text2)
’‘’

‘’‘stdout重定向到文件’‘’
console = sys.stdout                		# 得到当前输出方向, 也就是控制台
file = open(r".\file\data.txt", 'w')
sys.stdout = file                   				# 重定向到文件
print('hello\n'+'java\n'+'python') 	 	# 输出到文件
sys.stdout = console                		# 又回到控制台
print(33)                           					# 在控制台打印33


‘’‘
stdin重定向到文件
	在cmd输入语句
	python ***.py <filepath
‘’‘

‘’‘stdin重定位到文件’‘’
console = sys.stdin
file = open(r".\file\data.txt", 'r')
sys.stdin = file
content = input()                   				# 输入一行,不包含回车换行符
content2 = sys.stdin.readlines()    	# 输入其余内容,包含回车换行符,遇到文件尾自动结束输入
file.close()
print(content)
print(content2)
sys.stdin = console 							# 恢复定向
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值