Home > database >  Is there a way to execute a python code sequentially and with an underterminate amount of variables?
Is there a way to execute a python code sequentially and with an underterminate amount of variables?

Time:03-20

I've written a working python code using a predefined variable.

variable = "first_variable"

#code

with open(f"{variable}.txt", "w") as w_file:
    w_file.write("Something")

I now want to adapt the code to accept any number of variables as parameters and process them one after the other. In the shell, I would like to call it that way:

python3 code.py first_variable second_variable third_variable n_variable

Any idea on how i could do that? I tried using input, creating a function or with a while loop but failed...

CodePudding user response:

sys.argv is a list of all the arguments passed to python (starting with the name of your script). You can just iterate through each element of it like any other list:

import sys

for variable in sys.argv[1:]:
    with open(f"{variable}.txt", "w") as w_file:
        w_file.write("Something")

Note that sys.argv[0] will be code.py, which you probably don't want to overwrite.

CodePudding user response:

what you are trying to do is to get command line arguments.
According to command-line-arguments, you can obtain it from sys.argv, it gives you a list of parameter given by user:

>>> import sys
>>> print(sys.argv)
['demo.py', 'one', 'two', 'three']
  • Related