Python输入输出

本文详细介绍了Python中input()函数的使用,包括提示信息的设置,以及output()函数的参数sep、end的作用。讲解了如何通过sys.stdout实现控制台输出重定向到文件,并讨论了flush选项对输出刷新的影响。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

输入input() 函数

input([prompt])

  • Python3以上版本中 input() 函数接收一个标准输入数据,返回为 string 类型。
  • prompt: 提示信息。
  • 执行到input函数时,会停住,等待用户输入。
a = input("What would you like?"); print("I like the ", a)
执行结果:
What would you like?>? Apple	#此时光标处等待用户输入
I like the  Apple

输出函数print()

print(*objects, sep=’ ‘, end=’\n’, file=sys.stdout, flush=False)
可以输出各种类型。

sep and end

  • end, sep参数必须为str类型,或者为None。
print("Ideal is the beacon.", "********", "Without ideal, there is no secure direction.")
运行结果:
Ideal is the beacon. ******** Without ideal, there is no secure direction.
print("Ideal is the beacon.", "Without ideal, there is no secure direction.", "without direction , there is no life.",
 sep="---***---")
运行结果:
Ideal is the beacon.---***---Without ideal, there is no secure direction.---***---without direction , there is no life.
a = [3, 4, 5]
print("Ideal is the beacon.", a, "without direction, there is no life.", sep="---***---", end="stop\n")
运行结果:
Ideal is the beacon.---***---[3, 4, 5]---***---without direction , there is no life.stop

sys.stdout

当我们在 Python 中打印对象调用 print obj 时候,事实上是调用了 sys.stdout.write(obj+‘\n’)。
print 将需要的内容打印到了控制台,然后追加了一个换行符。
print 会调用 sys.stdout 的 write 方法。
以下两行在事实上等价:

sys.stdout.write('hello'+'\n') 
print('hello')

从控制台重定向到文件

  • 原始的 sys.stdout 指向控制台。
  • 如果把文件的对象的引用赋给 sys.stdout,那么 print 调用的就是文件对象的 write 方法。
  • 如果你还想在控制台打印一些东西的话,最好先将原始的控制台对象引用保存下来,向文件中打印之后再恢复 sys.stdout。
print("start")
f_handler = open('out.log', 'w')
print('Hi,Polly!', file=f_handler)
f_handler.close()
运行结果:
在控制台只会有start的打印。
在out.log会有Hi,Polly!的打印。
import sys
__console__=sys.stdout	#原始的 sys.stdout 指向控制台
f_handler=open('out.log', 'w')
sys.stdout=f_handler
print('Hello,Hanmeimei')
sys.stdout=__console__  #恢复控制台指向
print('Hello,Lucy')
运行结果:
在out.log会有Hello,Hanmeimei的打印。
在控制台只会有Hello,Lucy的打印。

flush

  • print() 函数会把内容放到内存中, 内存中的内容并不一定能够及时刷新显示到屏幕中。
  • 使用flush=True之后,会在print结束之后立即将内存中的东西显示到屏幕上,清空缓存。
  • 打开一个文件, 向其写入字符串, 在关闭文件之前, 打开文件是看不到写入的字符的。 要想在关闭之前实时的看到写入的字符串,用flush = True。
    如下图,在关闭文件之前,第二句的print语句并未写入文件。
    ![在这里插入图片描述](https://img-blog.csdnimg.cn/20210424213434822.png
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值