Three Standard Streams: stdin, stdout, stderr

本文介绍如何利用Python的sys.stdin、sys.stdout和sys.stderr进行代码调试,通过输入和输出来快速定位和解决程序中的bug。示例代码包括简单的单词计数脚本,演示了如何将文本文件作为输入源,并输出文本中单词的数量。
First, you shoud keep in mind that standard input/output is one of the best way to check bug. Because the data they offer is raw.
These are actually files (or file-like objects), and you can apply most of what you learn about files to them.

sys.stdin:

A standard source of data input is sys.stdin. When a program reads from standard input, you can supply text by typing it, or you can link it with the standard output of another program, using a pipe(This is a standard UNIX concept.)

sys.stdout:

The text you give to print appears in sys.stdout. The prompts for input and raw_input also go there. Data written to sys.stdout typically appears on your screen, but can be rerouted to the standard input of another program with a pipe, as mentioned.

sys.stderr:

Error messages (such as stack traces) are written to sys.stderr. In many ways, it is similar to sys.stdout

Simple Script That Counts the Words in sys.stdin:

# somescript.py
import sys
text = sys.stdin.read()
words = text.split()
wordcount = len(words)
print 'Wordcount:', wordcount 

file somefile.txt contain text like: 1 2 3 4 5 6 

Here are the results of linux command:  $cat somefile.txt | python somescript.py:

Wordcount: 6


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值