[ ]
宙飒天下网 1. 标准输入输出
python提供了标准输入输出的高级接口
input(prompt:str='')->str
prompt
是提示文本
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
file
: 默认为标准输出,但可以指定一个文件对象用于输出sep
: 字符串插入值之间,默认为空格。end
: 字符串附加在最后一个值之后,默认换行符。flush
: 是否强制冲洗替换流。
这两个接口一般也是我们从helloworld开始就接触到的东西.下面的例子展示了它的用法:
%%writefile src/stdio/helloworld.py def main(): who = input("你是谁?") print(f"hello world {who}!") if __name__ == "__main__": main()
Overwriting src/stdio/helloworld.py
1.1. 标准输入的低级接口
实际上上面这两个接口都是高级接口,是通过封装sys
模块下的对应接口实现的.
标准输入的低级接口是sys.stdin
,其有两个方法:
sys.stdin.read()
:读取数据ctrl+d
是结束输入.enter
是换行.故可以接受多行输入sys.stdin.readline()
:会将标准输入全部获取,包括末尾的'\n',因此用len计算长度时是把换行符'\n'算进去了的.遇到enter
结束,注意它是从第一个回车开始的
而sys.stdin
本身与可读文件对象具有相同的接口.
%%writefile src/stdio/helloworld_stdin.py import sys def main(): print("你是谁?") sys.stdin.readline() while True: line = sys.stdin.readline() if not line: break who = line.strip() print(f"hello world {who}!") if __name__ == "__main__": main()
Overwriting src/stdio/helloworld_stdin.py
1.2. 标准输出的低级接口
标准输出的低级接口是sys.stdout
,它是一个可写的文件对象.和它类似的是sys.stderr
.print
函数实际上就是调用的他们的write
方法,并且print
中也可以通过file
参数来指定一个有write
接口的可写文件对象来写入输出.
%%writefile src/stdio/helloworld_stdout.py import sys def main(): who = input("你是谁?") sys.stdout.write(f"hello world {who}!") if __name__ == "__main__": main()
Overwriting src/stdio/helloworld_stdout.py
还没有评论,来说两句吧...