sys.stdout 与 print
当我们在 Python 中打印对象调用 print obj 时候,事实上是调用了 sys.stdout.write(obj+'\n')
print 将你需要的内容打印到了控制台,然后追加了一个换行符
print 会调用 sys.stdout 的 write 方法
以下两行在事实上等价:
sys.stdout.write('hello'+'\n')
print 'hello'
sys.stdin 与 raw_input
当我们用 raw_input('Input promption: ') 时,事实上是先把提示信息输出,然后捕获输入
以下两组在事实上等价:
hi=raw_input('hello? ')
print 'hello? ', #comma to stay in the same line
hi=sys.stdin.readline()[:-1] # -1 to discard the '\n' in input stream
从控制台重定向到文件
原始的 sys.stdout 指向控制台
如果把文件的对象的引用赋给 sys.stdout,那么 print 调用的就是文件对象的 write 方法
f_handler=open('out.log', 'w')
sys.stdout=f_handler
print 'hello'
# this hello can't be viewed on concole
# this hello is in file out.log
记住,如果你还想在控制台打印一些东西的话,最好先将原始的控制台对象引用保存下来,向文件中打印之后再恢复 sys.stdout
同时重定向到控制台和文件
如果我们希望打印的内容一方面输出到控制台,另一方面输出到文件作为日志保存,那么该怎么办?
将打印的内容保留在内存中,而不是一打印就将 buffer 释放刷新,那么放到一个字符串区域中会怎样?
a=''
sys.stdout=a
print 'hello'
OK,上述代码是无法正常运行的
Traceback (most recent call last):
File ".\hello.py", line xx, in <module>
print 'hello'
AttributeError: 'str' object has no attribute 'write'
错误很明显,就是上面强调过的,在尝试调用 sys.stdout.write() 的时候,发现没有 write 方法
另外,这里之所以提示 attribute error 而不是找不到函数等等,我猜想是因为 python 将对象/类的函数指针记录作为对象/类的一个属性来对待,只是保留了函数的入口地址
既然这样,那么我们必须给重定向到的对象实现一个 write 方法:
一些背景sys.stdout 与 print当我们在 Python 中打印对象调用 print obj 时候,事实上是调用了 sys.stdout.write(obj+'\n')print 将你需要的内容打印到了控制台,然后追加了一个换行符print 会调用 sys.stdout 的 write 方法以下两行在事实上等价:sys.stdout.wri
一. 背景
在
Python
中,文件对象
sys
.stdin、
sys
.
stdout
和
sys
.stderr分别对应解释器的
标准
输入、
标准
输出
和
标准
出错流。在程序启动时,这些对象的初值由
sys
.__stdin__、
sys
.__
stdout
__和
sys
.__stderr__保存,以便用于收尾(finalization)时恢复
标准
流对象。
Windows系统中IDLE(
Python
GUI)由pyth
1.print
def print(self, *args, sep=' ', end='\n', file=None): # known special case of print
print(value, ..., sep=' ', end='\n', file=
sys
.
stdout
, flush=False)
Prints the values to a stream, or to
sys
.
stdout
by default.
Optional key
#本文纯菜鸟,所有博客为个人学习记录所用。不对的地方希望大家多多指教。
sys
.
stdout
: standard output file object; used by print()
sys
._
stdout
_ : the original
stdout
; don't touch!
从
sys
的help文档中对
sys
.
stdout
的定义得知,
sys
.
stdout
中存储的是
输出
去向的
1、
sys
.stdin.readline()与input
import
sys
#
sys
.stdin.readline() 相当于input,区别在于input不会读入'\n'
aa =
sys
.stdin.readline()
bb =...
Student.set_score = MethodType(set_score, Student)
Student.get_score = MethodType(get_score, Student)
t = Student(name="Bryan", age=24, score=80)
t2 = Student(name="Bryan", age=24, score=80)
# 输出80
print(t.score)
t.set_score(100)
t2.set_score(200)
print(t.get_score())
print(t.score)
# 200
[/code]
python dir()和vars()的区别
0FF1ine404:
python中MethodType的使用解析
jimmy-1112:
str_to_map hive 字符串转为map格式
i am cscs:
python中MethodType的使用解析
qq_29488527