Argparse tutorial example doesn't work in windows command line

随声附和 提交于 2021-01-05 08:58:20

问题


So I'm trying to teach myself how to use the python library argparse via the tutorial here. The example is given by the following piece of code which is saved as 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))

In the tutorial they put a $ before every command in the command line which is due to them using Linux I think. First if I add an $ in my windows command line before any command I get the error

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

If I then run

 python tut.py 1 2 3 4

I don't get an error but neither is any output displayed in the command line. What would be expected is the sum of those integers though.

How can I make the output show up in the command prompt ?


回答1:


At the beginning I didn't think that it was important to specify that I use the anaconda distribution for python, however it turns out that using the anaconda command prompt instead of the windos 10 one solves the problem.

Output

(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:


Use this code to get some of n passed arguments : 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))

OUTPUT

python tut.py 1 2 3 4   
10

Note: when I run your code it runs perfectly



来源:https://stackoverflow.com/questions/65200894/argparse-tutorial-example-doesnt-work-in-windows-command-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!