Ivi*_*vic 0 python python-2.7 argparse
我是python的新手。我正在编写一个计算单词、行和字符的程序。当我尝试使用命令行开关时,我开始遇到问题:-w、-l、-c,直到那时一切正常。
我阅读了有关 argparse 的 stackoverflow 和 python 文档的帖子,但我现在不知道如何实现 argparse 库以及与它一起使用的代码。
当我跑 python wc.py file.txt --l
我得到
太多值无法解压缩
有人可以帮我解决这个问题吗?
from sys import argv
import os.path
import argparse
script, filename = argv
def word_count(filename):
my_file = open(filename)
counter = 0
for x in my_file.read().split():
counter += 1
return counter
my_file.close()
def line_count(filename):
my_file = open(filename, 'r').read()
return len(my_file.splitlines())
my_file.close()
def character_count(filename):
my_file = open(filename, 'r').read()
return len(my_file)
my_file.close()
parser = argparse.ArgumentParser()
parser.add_argument('--w', nargs='+', help='word help')
parser.add_argument('--l', nargs='+', help='line help')
parser.add_argument('--c', nargs='+', help='character help')
args = parser.parse_args()
if os.path.exists(filename):
print word_count(filename), line_count(filename), character_count(filename)
else:
print "There is no such file"
Run Code Online (Sandbox Code Playgroud)
如果您argparse用于参数解析,则不应该尝试argv自己解析:
script, filename = argv
Run Code Online (Sandbox Code Playgroud)
如果argv少于两个元素,这将失败:
Traceback (most recent call last):
File "wc.py", line 5, in <module>
script, filename = argv
ValueError: need more than 1 value to unpack
Run Code Online (Sandbox Code Playgroud)
或者,如果有更多的比两个元素:
Traceback (most recent call last):
File "wc.py", line 5, in <module>
script, filename = argv
ValueError: too many values to unpack
Run Code Online (Sandbox Code Playgroud)
相反,您想使用argparse从参数列表中提取文件名:
parser.add_argument('filename')
Run Code Online (Sandbox Code Playgroud)
您现有的命令行参数也可以使用一些修复。取而代之的是:
parser.add_argument('--w', nargs='+', help='word help')
Run Code Online (Sandbox Code Playgroud)
你要:
parser.add_argument('-w', action='store_true', help='word help')
Run Code Online (Sandbox Code Playgroud)
这给了你这样的,如果用户通过一个布尔选项-w,然后args.w将True,否则None。这给你:
解析器 = argparse.ArgumentParser()
parser.add_argument('-w', action='store_true')
parser.add_argument('-c', action='store_true')
parser.add_argument('-l', action='store_true')
parser.add_argument('filename')
args = parser.parse_args()
if os.path.exists(args.filename):
print word_count(args.filename), line_count(args.filename), character_count(args.filename)
else:
print "There is no such file"
Run Code Online (Sandbox Code Playgroud)
您可能还想为您的选项提供长等价物:
parser.add_argument('--words', '-w', action='store_true')
parser.add_argument('--characters', '-c', action='store_true')
parser.add_argument('--lines', '-l', action='store_true')
Run Code Online (Sandbox Code Playgroud)
例如,通过此更改,用户可以使用-w或--words。然后args.words,您将拥有, args.characters, 和args.lines(而不是args.w, args.c, args.l)。