如何避免使用 python 处理空的标准输入?

编程入门 行业动态 更新时间:2024-10-26 07:38:44
本文介绍了如何避免使用 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 处理空的标准输入?

本文发布于:2023-10-13 00:28:56,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1486293.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:标准   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!