Search code examples
pythoncommand-line-argumentssys

Passing variable name as command line arguments in python


I want the user to enter the arguments using command line with variable names in the command line itself.

For example,

python test.py a=10 b=20

The code should be able to use a=10 and b=10 wherever needed.

I am able to achieve python test.py 10 20 but not the above given thing. I am wondering if that is even possible in python?


Solution

  • You cannot directly assign a variable from the command line, but sys.argv from the sys module will return a list of all your command line arguments. So you can pass the values, and then assign them in the first lines of your program like so.

    import sys
    # expect program to be run with "python test.py 10 20"
    file_name = sys.argv[0] # this will be "test.py" in our example
    a = sys.argv[1] # this will be 10
    b = sys.argv[2] # this will be 20
    

    Check out this article for more detailed information on this topic. https://www.geeksforgeeks.org/how-to-use-sys-argv-in-python/