如何检查fileinput是否为空?Python
我写了一个Python程序,可以在命令行中运行,用户可以输入要处理的文件。这些文件是通过fileinput读取的,并且可以使用optparse选项来处理它们。我的问题是,如果用户没有输入任何选项或文件名,程序就不会做任何事情,并且会继续运行。我希望程序在fileinput为空时,默认显示帮助选项。
有没有办法检查fileinput.input(argv)是否为空?当它为空时,它会默认使用标准输入,但我该如何在此之前检查它是否为空呢?
def parse_options():
parser = optparse.OptionParser()
parser.add_option('-o', '--output', dest='output',
default='c',
help='[c/f/h] output to (c)onsole, (f)ile or (h)tml')
parser.add_option('-s', '--sort', dest='sort',
default='pa',
help='[p/c/m/d] sort by (p)ath, (c)all frequency, (m)ean duration or (d)uration,\n'
'[a/d] sort by (a)scending or (d)escending order')
options, argv = parser.parse_args()
if options.output == 'f':
output_action = LogAnalyser.output_to_file
elif options.output == 'h':
output_action = LogAnalyser.output_to_html
else:
output_action = LogAnalyser.output_to_console
#if fileinput.input(argv) is None:
# parser.print_help()
# quit()
return output_action, options.sort, fileinput.input(argv)
1 个回答
1
好吧,如果 optparse
解析器返回了一个位置参数列表,你可以简单地检查这个列表是否为空:
(options, args) = parser.parse_args()
...
if args:
for line in fileinput.input(args):
...
如果这还不够,请详细说明你的问题。