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?
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.
(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>
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.