输入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语句并未写入文件。