企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
### 从键盘读入(标准输入) 从键盘读入后默认存为**字符串**,此处fd为字符串 ```python >>> fd = sys.stdin.read() hiyang ``` ### 标准输出 ```python >>> sys.stdout.write(fd+'\n') hiyang 或者 >>> print fd ``` ### 错误输出 ```python sys.stderr.write('hiyang') hiyang ``` ```python #!/usr/bin/env python import sys sys.stdout.write('this is stdout\n') sys.stderr.write('this is stderr\n') ``` 测试标准输出和错误输出 ```python # python std.py this is stdout this is stderr # python std.py 2> /dev/null this is stdout # python std.py > /dev/null this is stderr ``` --- ### 写文件 **write**写入方式,写入的内容必须为字符串 >>> fd = open('/tmp/a.txt','w') >>> fd.write(str(123)) **print**格式写入,追加还是覆盖取决于前面的打开方式 >>> fd = open('/tmp/a.txt','w') >>> print >> fd, 'hiyang' #### 两者关系 print >> sys.stdout,'hiyang' <==> sys.stdout.write('hiyang'+'\n') buffer 写入缓存 ```python >>> for i in range(10): sys.stdout.write('%s' % i) sys.stdout.flush() #刷新缓存 time.sleep(1) ``` 执行脚本文件,默认以行为输出单位 > 加'\n',或者加-u,或者 sys.stdout.flush()则无输出缓存 ```python #!/usr/bin/env python import sys import time for i in range(10): sys.stdout.write('%s\n' % i) time.sleep(1) ``` #### '\-' 数据流 使用数据流进行远程复制文件 ```python cat a.rpm | ssh ip 'cat - > a.rpm' ``` --- ### python 2 和 python 3 print语句的比较 | python 2.6 |python 3.0 | 说明 | |----|----|----| |print x, y | print(x, y) | 对象输出sys.stdout.write(),并在各项间添加空格,末尾换行| |print x, y, | print(x, y , end='') | 同上,但是行末不换行 | |print >> afile, x, y |print(x, y, file=afile) | 把文件发送到myfile.write() | #### python 2 print语句向后兼容方法 ~~~ from __future__ import print_function from __future__ import print_function print('bad!' * 8, file=sys.stderr) bad!bad!bad!bad!bad!bad!bad!bad! ~~~ #### python 3 print函数 ``` print([object, ...][, sep=' '][, end='\n'][, file=sys.stdout]) ``` `sep` 是在每个对象的文本之间插入一个字符串,默认是单个空格 `end` 添加在打印文本末尾的字符串,默认是'\n',传递一个空格将避免行尾换行 `file` 指定要发送到的文件,默认是sys.stdout;如果是真正的文件,文件应处于打开状态 `print(x, y, z, sep='...', file=open('data.txt', w))` 要想更加具体灵活的格式,可以打印前提前格式化即可。 ### 自动化流重定向 通过赋值sys.stdout将打印文字重定向,需要先保存sys.stdout对象,完成后再恢复即可 在ipython下测试失败,在python中测试OK ``` import sys tmp = sys.stdout sys.stdout = open('log.txt', 'a') print 'hiyang', print 'hiyang', sys.stdout.close() sys.stdout = tmp ``` ## Python input和raw_input的区别 使用input和raw_input都可以读取控制台的输入,但是input和raw_input在处理数字时是有区别的 纯数字输入 当输入为纯数字时 input返回的是数值类型,如int,float raw_inpout返回的是字符串类型,string类型 输入字符串为表达式 input会计算在字符串中的数字表达式,而raw_input不会。 如输入 “57 + 3”: input会得到整数60 raw_input会得到字符串”57 + 3” python input的实现 看python input的文档,可以看到input其实是通过raw_input来实现的,原理很简单,就下面一行代码: ~~~ def input(prompt): return (eval(raw_input(prompt))) ~~~