逛着博客园,看到乙醇大佬的一篇随笔 https://www.cnblogs.com/nbkhic/p/9370446.html,于是就在想怎么测试这句hello world

print('hello world')

想法是修改stdout的指向到一个io.StringIO流中,然后把流中的数据与‘hello world’去比较,可是写完之后发现,程序虽然没报错,但是流中无数据写入,百思不得其解;只好换成文件流,代码如下:

import sys

def hi():
print('hello world') if __name__ == '__main__':
old = sys.stdout with open('test','w') as oFile:
sys.stdout = oFile
hi() sys.stdout = old with open('test','r') as oFile:
if 'hello world' + '\n' == oFile.readline():
print('PASS')
else:
print('FAIL',file=sys.stderr)

结果也输出了PASS

C:\Users\suneee\AppData\Local\Programs\Python\Python36\python.exe E:/wangjz/PyWorkSpace/LearnPython/test.py
PASS Process finished with exit code 0

PS:至于比较字符串‘hello world’后面为什么要加个'\n',可以看下print函数说明

def print(*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 keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
"""
pass

最新文章

  1. UITextFeild的用法
  2. list转map 键值对
  3. Log4j乱码
  4. .net 页面跳转方式【转】
  5. 机器学习之三:logistic回归(最优化)
  6. 【Android O】 Service AAA does not have a SELinux domain defined
  7. VMware Workstation Pro 安装win7系统
  8. 项目管理、软件、禅道 VS JIRA
  9. oracle数据库添加新用户
  10. 解决在Mac的Vmware Fusion中装win7系统和mac原生系统直接切换win7系统分辨率变化的问题
  11. OD之修改文件标题(一)
  12. 还没被玩坏的robobrowser(5)——Beautiful Soup的过滤器
  13. 优化cocos2d/x程序的内存使用和程序大小
  14. Maven项目下启动后Eclipse报错:org.springframework.web.context.ContextLoaderListener
  15. linux内核分析 第六周 分析Linux内核创建一个新进程的过程
  16. Tomcat自带log的配置详解
  17. Django 笔记(来源于讲师)以及常见问题的解决
  18. JS实现表格列宽拖动
  19. Solr之困
  20. C# 用tabcontrol实现窗体类似网页排版的显示

热门文章

  1. You Can Customize Synthesized Instance Variable Names @property
  2. vue 命名路由
  3. .ckpt文件与.pb文件
  4. node.js封装数据库增删改查
  5. SDOI2019快速查询
  6. HDU 6212 Zuma
  7. OpenGL的核心模式与立即渲染模式
  8. OpenCV2 与opencv3 问题解决
  9. zookeeper核心原理全面解析
  10. MLflow系列1:MLflow入门教程(Python)