1

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?

Gabio
  • 9,126
  • 3
  • 12
  • 32
A. Gehani
  • 83
  • 7
  • 1
    Does this answer your question? [Reading named command arguments](https://stackoverflow.com/questions/40001892/reading-named-command-arguments) – esqew Sep 30 '21 at 05:07
  • It sounds like what you're asking is "if I specify ```a=10``` on the command line, is there some way I can reference a variable ```a``` with the value ```10``` in the script" ? – sj95126 Sep 30 '21 at 05:09

3 Answers3

0

You can use sys and getopt to do this in a similar fashion to how you would check for command-line arguments in C. You can see if this is the right choice for your use-case by reading the documentation here.

Lucas Roy
  • 133
  • 1
  • 7
0

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/

Andrew-Harelson
  • 1,022
  • 3
  • 11
0

You can do something like this (very hacky):

import sys

def assign_variable_dynamically(expression):
    var_name, value = expression.split("=")
    globals()[var_name] = value

# for the following run: python test.py a=10 b=20
# you will get:
assign_variable_dynamically(sys.argv[1]) 
assign_variable_dynamically(sys.argv[2])
print(a)  # output: 10
print(b)  # output: 20
Gabio
  • 9,126
  • 3
  • 12
  • 32
  • @A.Gehani please pay attention that the above solution works for expressions of the form `var_name=value_name` – Gabio Sep 30 '21 at 06:59