Home > Back-end >  How do i replace inputs with command line arguments
How do i replace inputs with command line arguments

Time:12-24

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)

CodePudding user response:

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

CodePudding user response:

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
  • Related