Christian Singer
Christian Singer

Reputation: 305

Argparse tutorial example doesn't work in windows command line

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 ?

Upvotes: 1

Views: 1432

Answers (2)

Christian Singer
Christian Singer

Reputation: 305

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>

Upvotes: 1

Yash Makan
Yash Makan

Reputation: 764

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

Upvotes: 0

Related Questions