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!
CodePudding user response:
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']
CodePudding user response:
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])
