Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/303.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/jsp/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将变量名作为命令行参数传递到打印_Python_Command Line Arguments - Fatal编程技术网

Python 将变量名作为命令行参数传递到打印

Python 将变量名作为命令行参数传递到打印,python,command-line-arguments,Python,Command Line Arguments,我想知道这是否可能 a = 100 b = 200 c = 300 print(argv[1]) 我想在argv[1]=a时打印a的值,即当我以 python test.py a 输出应为100 其他变量b和c也是如此。有可能吗?您可以使用字典来实现这一点: to_print = { "a": 100, "b": 200, "c": 300 } print(to_print.get(argv[1])) 使用命令: d = {"a": 100, "b": 200, "c":

我想知道这是否可能

a = 100
b = 200
c = 300

print(argv[1])
我想在
argv[1]=a
时打印a的值,即当我以

python test.py a 
输出应为
100


其他变量
b
c
也是如此。有可能吗?

您可以使用字典来实现这一点:

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

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

使用
命令

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

print(d.get(argv[1]))
使用字典:

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

是的,你可以。我不确定你是否应该,但你可以这样做:

import sys

a = 100
b = 200
c = 300

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

您可以使用以下代码:

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

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

顺便说一句,我看到许多其他人给出了关于从字典而不是从全局变量中检索值的答案。虽然这些答案并不符合OP的要求,但我相信它们是更好的实践。我不会在我自己的代码中真正执行
globals()[sys.argv[1]]