【发布时间】:2015-05-30 05:12:58
【问题描述】:
我有这个程序,它应该允许用户输入开始/结束 arg 以及文件 arg,然后程序将打开一个 txt 文件并读取从 args 开始和结束的 line line s。但是如果我输入 2 作为开始,输入 10 作为结束,它给我的 end 必须大于 start 错误。我该如何解决这个问题?
#/usr/bin/python
# File name: print_lines.py
import sys
print sys.argv[1]
print sys.argv[2]
if len(sys.argv) != 4:
print "Input: print.py starting ending\n"
exit ()
if sys.argv[1] >= sys.argv[2]:
print "Ending line must be larger than the starting line.\n"
sys.exit()
start = int(sys.argv[1])
end = int(sys.argv[2])
textinput = str(sys.argv[3])
current = 1
try:
with open(textinput, 'r') as text:
for line in text:
if current >= start and current <=end:
print line
current += 1
if current > end:
break
else:
print "End reached, line finishes at", current-1
except IOError:
print "File not found. \n"
sys.exit()
【问题讨论】:
标签: python command-line-arguments