var1 = "plzHalp"
cmd = input("> ")
subcmd = cmd.split(" ")
if subcmd[0] == "set" and subcmd[1] in setL:
secondOp = subcmd[1]
cmdVar = subcmd[2]
eval(subcmd[1]) = subcmd[2]
print("[Set",secondOp,"==>",cmdVar)
我想要这样做,分配子命令的第二部分(subcmd [1])并将预制变量更改为第三部分(subcmd [2])。 例如。如果命令是"设置var1 fixedYay"然后var1将等于" fixedYay"。
答案 0 :(得分:0)
如果我正确理解您的问题,您需要将eval(subcmd[1])
替换为globals()[subcmd[1]]
。请参阅下面的示例并阅读globals()和locals()函数。
C:\Users\nagul>python
Python 3.5.0 (v3.5.0:374f501f4567, Sep 13 2015, 02:16:59) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> var1='plzHalp'
>>> var1_str='var1'
>>> print(globals()[var1_str])
plzHalp
>>> globals()[var1_str]='fixedYay'
>>> print(var1)
fixedYay
>>>