简体   繁体   中英

Passing variable name as command line argument to print

I was wondering if this is possible

a = 100
b = 200
c = 300

print(argv[1])

I want to print value of a when argv[1] = a , ie when I run program from command line as

python test.py a 

Output should be 100 .

And same for other the variables b and c . Is it something possible?

Yes, you can. I'm not sure you should, but you can, this way:

import sys

a = 100
b = 200
c = 300

print(globals()[sys.argv[1]])

You can use dictionaries to achieve this:

to_print = {
  "a": 100,
  "b": 200,
  "c": 300
}

print(to_print.get(argv[1]))

Use a dict :

d = {"a": 100, "b": 200, "c": 300}

print(d.get(argv[1]))

Use a dictionary:

values = {'a': 100, 'b': 200, 'c': 300}
print(values[argv[1]])

You can use below code:

import sys
values = {'a': 100, 'b': 200, 'c': 300}

if __name__ == "__main__":
    try:
        print(values[sys.argv[1]])
    except KeyError:
        print("Provide correct arguments")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM