gpt4 book ai didi

python - 如何实现命令行切换到我的脚本?

转载 作者:行者123 更新时间:2023-12-02 17:31:45 26 4
gpt4 key购买 nike

我是 python 的新手。我正在编写一个计算单词、行和字符的程序。当我尝试使用命令行开关时,我开始遇到问题:-w、-l、-c,直到那时一切正常。

我阅读了关于 argparse 的 stackoverflow 和 python 文档的帖子,但我现在不知道如何实现 argparse 库以及与之一起使用的代码。

当我运行 python wc.py file.txt --l

我明白了

too many values to unpac

有人可以帮我解决这个问题吗?

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"

最佳答案

如果您使用 argparse 进行参数解析,您不应该尝试自己解析 argv:

script, filename = argv

如果 argv 的元素少于两个,这将失败:

Traceback (most recent call last):
File "wc.py", line 5, in <module>
script, filename = argv
ValueError: need more than 1 value to unpack

或者如果它有多于两个元素:

Traceback (most recent call last):
File "wc.py", line 5, in <module>
script, filename = argv
ValueError: too many values to unpack

您反而想使用 argparse 从参数列表中提取文件名:

parser.add_argument('filename')

您现有的命令行参数也可以使用一些修复。而不是这个:

parser.add_argument('--w', nargs='+', help='word help')

你想要:

parser.add_argument('-w', action='store_true', help='word help')

这为您提供了一个 bool 选项,如果用户传递 -w,则 args.w 将为 True,否则为 。这给你:

解析器 = 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"

您可能还想为您的选项提供长等效项:

parser.add_argument('--words', '-w', action='store_true')
parser.add_argument('--characters', '-c', action='store_true')
parser.add_argument('--lines', '-l', action='store_true')

通过此更改,例如,用户可以使用 -w--words。然后您将拥有 args.wordsargs.charactersargs.lines(而不是 args.w , args.c, args.l).

关于python - 如何实现命令行切换到我的脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32286403/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com