argparse - 要求已经给出的参数

argparse - asks for argument that's already been given

我正尝试使用以下命令 运行 我的文件:

python3 file.py -p pony_counts num_words

我的 argparse 代码是:

parser = argparse.ArgumentParser()

parser.add_argument('pony_counts', type=str, help="output file for compute_pony_lang.py")    
parser.add_argument('num_words', type=int, help="num of words we want in the output list for each speaker")
parser.add_argument('-p', action='store_true')

args = parser.parse_args()

with open(args.pony_counts) as f:
    df = json.load(f)
    
df = pd.DataFrame(df) # convert json to df
df = df.drop([i for i in df.index if i.isalpha() == False]) # drop words that contain apostrophe

total_words_per_pony = df.sum(axis=0) # find total no. of words per pony
df.insert(6, "word_sum", df.sum(axis=1)) # word_sum = total occurrences of a word (e.g. said by all ponies), in the 7th column of df
tf = df.loc[:,"twilight":"fluttershy"].div(total_words_per_pony.iloc[0:6]) # word x (said by pony y) / word x (total occurrences)
    
ponies_tfidf = tfidf(df, tf)  
ponies_alt_tfidf = tfidf(df, tf)      

d = {}
ponies = ['twilight', 'applejack', 'rarity', 'pinky', 'rainbow', 'fluttershy']

if args.p:
   for i in ponies:
       d[i] = ponies_alt_tfidf[i].nlargest(args.num_words).to_dict()
else: # calculate tfidf according to the method presented in class 
   for i in ponies:
       d[i] = ponies_tfidf[i].nlargest(args.num_words).to_dict()

final = {}
for pony, word_count in d.items():
    final[pony] = list(word_count.keys())  

pp = pprint.PrettyPrinter(indent = 2)
pp.pprint(final)

我的代码 运行s 与命令 - 然而,else 块 运行s 无论命令是否包含 -p 参数。非常感谢帮助,谢谢!

运行命令:

python3 file.py -p 10

相当于:

python3 file.py -p=10

在 Bash 中(假设您在 Mac 或 Linux 上),空格被视为与标志后的等号相同。因此,如果您想为 -p 标志传递一个值,您需要将其结构化为:

python3 file.py -p <tfidf arg> <pony_counts> <num_words>

只是阅读您的代码,也许您希望 -p 成为真/假标志而不是输入?如果是这样,您可以使用 action='store_true'action='store_false'。它指出了如何做到这一点 in the docs。从文档中提取示例:

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', action='store_true')
>>> parser.add_argument('--bar', action='store_false')
>>> parser.add_argument('--baz', action='store_false')
>>> parser.parse_args('--foo --bar'.split())
Namespace(foo=True, bar=False, baz=True)