如何避免使用 python 处理空的标准输入? [英] How do I avoid processing an empty stdin with python?
问题描述
sys.stdin.readline()
在返回之前等待 EOF(或新行),所以如果我有一个控制台输入,readline()
等待用户输入.相反,如果没有要处理的内容,我想打印帮助并以错误退出,而不是等待用户输入.
The sys.stdin.readline()
waits for an EOF (or new line) before returning, so if I have a console input, readline()
waits for user input. Instead I want to print help and exit with an error if there is nothing to process, not wait for user input.
原因:我正在寻找编写一个命令行行为类似于 grep
的 python 程序.
Reason:
I'm looking to write a python program with command line behaviour similar to grep
.
测试用例:
无输入,无管道,打印帮助
No input and nothing piped, print help
$ argparse.py
argparse.py - prints arguments
echo $? # UNIX
echo %ERRORLEVEL% # WINDOWS
2
解析命令行参数
$ argparse.py a b c
0 a
1 b
2 c
接受管道命令
$ ls | argparse.py
0 argparse.py
1 aFile.txt
parseargs.py 列表:
parseargs.py listing:
# $Id: parseargs.py
import sys
import argparse
# Tried these too:
# import fileinput - blocks on no input
# import subprocess - requires calling program to be known
def usage():
sys.stderr.write("{} - prints arguments".fomrat(sys.argv[0])
sys.stderr.flush()
sys.exit(2)
def print_me(count, msg):
print '{}: {:>18} {}'.format(count, msg.strip(), map(ord,msg))
if __name__ == '__main__':
USE_BUFFERED_INPUT = False
# Case 1: Command line arguments
if len(sys.argv) > 1:
for i, arg in enumerate(sys.argv[1:]):
print_me( i, arg)
elif USE_BUFFERED_INPUT: # Note: Do not use processing buffered inputs
for i, arg in enumerate(sys.stdin):
print_me( i, arg)
else:
i=0
##### Need to deterime if the sys.stdin is empty.
##### if READLINE_EMPTY:
##### usage()
while True:
arg = sys.stdin.readline() #Blocks if no input
if not arg:
break
print_me( i, arg)
i += 1
sys.exit(0)
推荐答案
grep
可以按照它的方式工作,因为它有一个非可选参数:模式.例如
grep
can work the way it does because it has one non-optional argument: the pattern. For example
$ grep < /dev/zero
Usage: grep [OPTION]... PATTERN [FILE]...
Try `grep --help' for more information.
即使 stdin 上有无限的输入可用,grep 也没有得到所需的参数,因此抱怨.
even though there was infinite input available on stdin, grep didn't get the required argument and therefore complained.
如果您只想使用可选参数并在 stdin 是终端时出错,请查看 file.isatty().
If you want to use only optional arguments and error out if stdin is a terminal, look at file.isatty().
这篇关于如何避免使用 python 处理空的标准输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!