0

Is there a way to define command line arguments in Python, but the number of those argument changes?

For example I have this list:

arguments = [arg1, arg2, arg3]

My script would be invoked from another place like this:

python3 python_script.py arg1 arg2 arg3

But, the number of arguments could change:

python3 python_script.py arg1 arg2 arg3 arg4 arg5

So, is there a way to make sure that array is extendable?

Thank you in advance!

Belphegor
  • 49
  • 5
  • 1
    Does this answer your question? [Argparse: how to handle variable number of arguments (nargs='\*')](https://stackoverflow.com/questions/20165843/argparse-how-to-handle-variable-number-of-arguments-nargs) – S4eed3sm Feb 02 '22 at 06:10
  • Luckily it's not an array but an extendable list. – Klaus D. Feb 02 '22 at 06:10
  • @S4eed3sm thank you for your reply, that helped a lot, I read the comments on that page and managed to find the solution for setup. Thank you very much! – Belphegor Feb 02 '22 at 10:26

2 Answers2

0

The number of args is variable already. This is a property of your shell not of python. You can get the list with sys.argv.

# run.py
import sys
print(sys.argv)
python3 run.py a b c d
>>> ['run.py', 'a', 'b', 'c', 'd']
nlta
  • 1,716
  • 1
  • 7
  • 17
  • Thank you for the fast reply! Do you have a suggestion on how to use those arguments later in the script? I was thinking if something like this is possible: arguments = [arg1, arg2, [expect a list of arguments or one], arg3]? – Belphegor Feb 02 '22 at 06:15
  • 1
    Are you trying to validate some property of the list ? Eg. There is more than 1 arg? Add that to your post if so. – nlta Feb 02 '22 at 06:18
0

Inside the python script use the variable len(sys.argv) to figure out how many arguments are passed to the python script.

Create the arguments array based on the value from len(sys.argv) and then do the required operations on the array arguments

import sys
n = len(sys.argv)
arguments = []
for i in range(1,n):
    arguments.append(sys.argv[i])
Teja Goud Kandula
  • 1,462
  • 13
  • 26