So im making a program where one of the requirements is to use command line arguments and not normal inputs(). I've read about the sys module and have tried it out myself but I still dont know how to replace my inputs with these arguments. I have made a very simple code with 2 inputs incase you want to show me how to do it. So the question basically is how to convert these inputs to command line arguments using sys. Thanks for the help in advance !
number1 = int(input("Enter a number:"))
number2 = int(input("Enter a number:"))
number = number1 + number2
print(number)
It save args.numbers as list of input numbers
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-nbs', '--numbers', nargs='+', default=[], help="Get numbers from command line")
if args.numbers:
print("Numbers " + str(args.numbers)
To run:
python run.py --numbers 10 12 11 14
sys.argv
contains the arguments you passed at the command line when running your script:
import sys
print(
f"The name of the script is {sys.argv[0]} "
f"and the arguments are {sys.argv[1:]}"
)
% python test.py 2 3
The name of the script is test.py and the arguments are ['2', '3']
import sys
print(sum(map(int, sys.argv[1:])))
% python test.py 2 3
5
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.