【问题标题】:Argparse tutorial example doesn't work in windows command lineArgparse 教程示例在 Windows 命令行中不起作用
【发布时间】:2021-03-19 21:22:47
【问题描述】:

所以我试图通过教程here 教自己如何使用python 库argparse。示例由以下代码段给出,保存为tut.py

import argparse

parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
                help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
                const=sum, default=max,
                help='sum the integers (default: find the max)')

args = parser.parse_args()
print(args.accumulate(args.integers))

在教程中,他们在命令行中的每个命令之前都放置了一个$,我认为这是因为他们使用的是 Linux。首先,如果我在我的 Windows 命令行中添加一个 $ 在任何命令之前我会收到错误

The "$" command was either misspelled or could not be found.

如果我再跑

 python tut.py 1 2 3 4

我没有收到错误消息,但命令行中也没有显示任何输出。不过,可以预期的是这些整数的总和。

如何使输出显示在命令提示符中?

【问题讨论】:

  • $ 只是在linux终端中表示一个新行,你可以忽略它
  • 如果你设置print(args.accumulate(args.integers), flush=True)会发生什么?
  • 如果要打印整数的总和,请尝试使用 sum() 函数而不是 accum()
  • @HirushaFernando OP 希望利用--sum 标志设置的默认值,即max,如果通过了sum 标志,它将切换到sum,如下所示constdefault kwargs,所以 args.accumulate 是正确的
  • @C.Nivs 设置 flush = True 也不会产生任何输出

标签: python command-line argparse


【解决方案1】:

一开始我并不认为指定我为 python 使用 anaconda 发行版很重要,但事实证明使用 anaconda 命令提示符而不是 windows 10 可以解决问题。

输出

(base) C:\Users\Admin\Desktop\HiWi\Codect>python tut.py 1 2 3 4
4

(base) C:\Users\Admin\Desktop\HiWi\Codect>python tut.py 1 2 3 4 --sum
10

(base) C:\Users\Admin\Desktop\HiWi\Codect>

【讨论】:

    【解决方案2】:

    使用此代码获取 n 个传递的参数中的一些: tut.py

    import argparse
    
    parser = argparse.ArgumentParser(description='Process some integers.')
    parser.add_argument('integers', metavar='N', type=int, nargs='+',
                    help='an integer for the accumulator')
    parser.add_argument('--sum', dest='accumulate', action='store_const',
                    const=sum, default=max,
                    help='sum the integers (default: find the max)')
    
    args = parser.parse_args()
    print(sum(args.integers))
    

    输出

    python tut.py 1 2 3 4   
    10
    

    注意:当我运行您的代码时,它会完美运行

    【讨论】:

    • 嗯,很有趣。在我的情况下它仍然没有显示任何输出
    • 事实上,确实如此。我在我的 Windows 10 机器上运行了相同的脚本,这很有效。检查你的 cmd 命令
    • 在 cmd 中尝试 echo hi。它会打印什么东西吗?
    • 是的,它会打印“hi”
    • 现在制作一个 python 脚本,它简单地通过print('hi') 打印 hi 并由 cmd 运行。它打印什么吗?
    猜你喜欢
    • 2023-01-30
    • 2014-01-21
    • 1970-01-01
    • 1970-01-01
    • 2015-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-26
    相关资源
    最近更新 更多