之前只是在项目中看到过,没怎么注意,正好跟对象一起看python学习手册,看到了这个部分于是来研究下。

python版本 2.7.x
os  win7

print

 一般就是执行脚本的时候,把信息直接打印到标准输出,也就是我们通常说的控制台
print是python __builtin__ 中的一个方法,来看看他的定义
  1. def print(stream):
  2. """ print(value, ..., sep=' ', end='\\n', file=sys.stdout)
  3.  
  4. Prints the values to a stream, or to sys.stdout by default.
  5. Optional keyword arguments:
  6. file: a file-like object (stream); defaults to the current sys.stdout.
  7. sep: string inserted between values, default a space.
  8. end: string appended after the last value, default a newline. """
  9. pass
从这里我们就能看到print也许比我们常用的功能多一些
* sep 用来做values之间的分割符,所以当我们 print '2', 'a' 的时候,实际中间是空格
* end 默认是换行,所以print总是打印一行信息
* 其实print还可以输出到文件中
但我们又知道python2中的print 后面是没有参数列表的
  1. In [2]: print ('a', 'b', sep='|')
  2. File "<ipython-input-2-bcb798285c07>", line 1
  3. print ('a', 'b', sep='|')
  4. ^
  5. SyntaxError: invalid syntax

哦噢,报错了,其实只要 from __future__ import print_function 就可以像python3一样使用参数了
  1. In [6]: print('a', 'b')
  2. a b
  3.  
  4. In [7]: print('a', 'b', sep='--') #print 多个values 不用逗号分隔
  5. a--b
  6.  
  7. In [8]: print('nihao');print('orangle')
  8. nihao
  9. orangle
  10.  
  11. In [9]: print('nihao', end='');print('orangle') #print 不换行
  12. nihaoorangle

好像print也有不少玩法哦
我们直接把print的值写到文件对象中,而不是默认的sys.stout试
  1. In [11]: f = open('test.txt', 'w')
  2. In [12]: print('haha.....csdn', file=f)
  3. In [15]: ls test.txt
  4. 驱动器 D 中的卷没有标签。
  5. 卷的序列号是 0002-FA2E
  6. D:\code\python 的目录
  7. 2015/01/20 周二 10:37 0 test.txt
  8. 1 个文件 0 字节
  9. 0 个目录 61,124,526,080 可用字节
  10. In [16]: f.close()
到对应的目录下看看,test.txt的内容,果然是 haha.....csdn, 不过一定要记得 f.close(), 如果不关闭,内容是无法保存到文件中的。

sys.stdout.write

这个方法调用的是 ,file 对象中的write方法 ,把字符写到标准输出中,看起来跟print 差不多。
  1. def write(self, str):
  2. """ write(str) -> None. Write string str to file.
  3.  
  4. Note that due to buffering, flush() or close() may be needed before
  5. the file on disk reflects the data written. """
  6. return ""

关系

这个方法和print什么关系呢? 我们来查查
可以认为 print是对 sys.stdout.write的友好封装,也只是从 python学习手册这样看到。

区别

print 可以把一个对象转化成str然后放到标准输出中, sys.stdout.write 需要把对象先转化成对象在输出
  1. In [3]: class A():
  2. ...: def __str__(self):
  3. ...: return "A"
  4. ...:
  5.  
  6. In [5]: a = A()
  7. In [6]: print a
  8. A
  9.  
  10. In [9]: import sys
  11. In [10]: sys.stdout.write(a)
  12. ---------------------------------------------------------------------------
  13. TypeError Traceback (most recent call last)
  14. <ipython-input-10-0697f962911e> in <module>()
  15. ----> 1 sys.stdout.write(a)
  16.  
  17. TypeError: expected a character buffer object
  18.  
  19. In [11]: sys.stdout.write(str(a))
  20. A
所以说不能用 sys.stdout.write来直接代替 print


运用

这里两者怎么结合使用?
引用 Learning Python 中的一段代码
  1. import sys
  2. temp = sys.stdout #store original stdout object for later
  3. sys.stdout = open('log.txt','w') #redirect all prints to this log file
  4. print("testing123") #nothing appears at interactive prompt
  5. print("another line") #again nothing appears. It is instead written to log file
  6. sys.stdout.close() #ordinary file object
  7. sys.stdout = temp #restore print commands to interactive prompt
  8. print("back to normal") #this shows up in the interactive prompt

log.txt文件中保存输出结果为
  1. testing123
  2. another line
我们可以把调试中打印的信息保存的文件中,这样也是追中和查找错误的一个方式
还有就是多线程日志中可能会用到
sys.stdout.write 来封装日志写入


参考文章:

[Python]print vs sys.stdout.write的更多相关文章

  1. PyQt(Python+Qt)学习随笔:print标准输出sys.stdout以及stderr重定向QTextBrowser等图形界面对象

    专栏:Python基础教程目录 专栏:使用PyQt开发图形界面Python应用 专栏:PyQt入门学习 老猿Python博文目录 <在Python实现print标准输出sys.stdout.st ...

  2. sys.stdout.write和print和sys.stdout.flush

    1. 先看下官方文档 """ sys.stdout.write(string) Write string to stream. Returns the number of ...

  3. 在Python实现print标准输出sys.stdout、stderr重定向及捕获的简单办法

    专栏:Python基础教程目录 专栏:使用PyQt开发图形界面Python应用 专栏:PyQt入门学习 老猿Python博文目录 Python中的标准输出和错误输出由sys模块的stdout.stde ...

  4. print和sys.stdout

    print print语句执行的操作是一个写操作,把我们从外设输入的数据写到了stdout流,并进行了一些特定的格式化.和文件方法不同,在执行打印操作是,不需要将对象转换为字符串(print已经帮我们 ...

  5. python 标准输入输出sys.stdout. sys.stdin

    import sys, time ## print('please enter your name:')# user_input=sys.stdin.readline()# print(user_in ...

  6. 关于print()、sys.stdout、sys.stderr的一些理解

    print() 方法的语法: print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False) 其中file = sys.stdout的 ...

  7. Python之print(args)与sys.stdout.write(string)使用总结

    一.sys.stdout.write(string) import sys; # sys.stdout.write(): # 1.默认不换行 # 2.参数必须是字符串 # demo 01 x = &q ...

  8. 【python】print · sys.stdout · sys.stderr

    参考文档 Python重定向标准输入.标准输出和标准错误 http://blog.csdn.net/lanbing510/article/details/8487997 python重定向sys.st ...

  9. 【Python】【Head First Python】【chapter1】2 - sys.stdout 和 print 的区别

    sys.stdout 和 print 的区别 首先,通过 help(print) 得到print内建函数的参数 Help on built-in function print in module bu ...

随机推荐

  1. 【Android学习笔记】布局的简单介绍

    我在学习Android开发的时候是基于实战项目的,基础理论知识以前也是零散的看过一些,个人还是觉得边做项目边学要快些.现在做的这个项目iOS端是我做的,这样逻辑什么的都很熟悉,于我而言换个平台也只是换 ...

  2. [BeiJing2011]元素

    Description 相传,在远古时期,位于西方大陆的 Magic Land 上,人们已经掌握了用魔 法矿石炼制法杖的技术.那时人们就认识到,一个法杖的法力取决于使用的矿石. 一般地,矿石越多则法力 ...

  3. 【网络流】【BZOJ1006】【SCOI2007】蜥蜴

    学弟@lher在周末训练赛中出的题目的原题(这个人拿省选题来当作提高组模拟,太丧了...) 题意简析:看题目:) 解题思路:题目显然是最大流. 首先拆点将点权变为边权,然后按照题意对于所有有跳板的点向 ...

  4. bzoj 2229: [Zjoi2011]最小割

    Description 小白在图论课上学到了一个新的概念--最小割,下课后小白在笔记本上写下了如下这段话: "对于一个图,某个对图中结点的划分将图中所有结点分成两个部分,如果结点s,t不在同 ...

  5. poj 1755 半平面交+不等式

    Triathlon Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 6461   Accepted: 1643 Descrip ...

  6. poj 1696 叉积理解

    Space Ant Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 3967   Accepted: 2489 Descrip ...

  7. TensorFlow官方文档

    关于<TensorFlow官方文档> <TensorFlow官方文档>原文地址:http://devdocs.io/tensorflow~python/ ,本次经过W3Csch ...

  8. Json数组删除

    有一个json数组,{'people':[{'name':'jetty','sex':'男'},{'name':'lily','sex':'女'}]} 有一个json:var aa={'name':' ...

  9. Mysql B-Tree, B+Tree, B*树介绍

    [摘要] 最近在看Mysql的存储引擎中索引的优化,神马是索引,支持啥索引.全是浮云,目前Mysql的MyISAM和InnoDB都支持B-Tree索引,InnoDB还支持B+Tree索引,Memory ...

  10. js保留两位小数数字

    /* * @descript: 保留两位小数,如果小数点大于两位小数,就向上取值保留两位小数<br/> * @time 2016-07-13 */function mathCeil(num ...