简体   繁体   English

将变量名作为命令行参数传递给print

[英]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 我想在argv[1] = a a时打印a的值,即当我从命令行运行程序时

python test.py a 

Output should be 100 . 输出应为100

And same for other the variables b and c . 对于其他变量bc 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 : 使用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")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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