0

我有一个充满变量的库(我不想手动编辑),它看起来像这样:

def get_variables(gateway):
    variables={
        'gateway':gateway, 
        'license_test_data':gateway['license_data'],
        'license_for_application':gateway['license_for_application'],
        'Valid_Login_Test_Vairables':{'valid_ssh_command':['ssh '+gateway['DeviceUnderTestUserid']+'@'+gateway['DeviceUnderTestIP'],'password:']}
        #around 3000 more just like this or worse
       }
return variables

我需要将此信息导入 python 数据结构而不替换“网关”变量。换句话说,我希望能够:

print vars['Valid_Login_Test_Vairables']['valid_ssh_command']

并得到这个

'ssh +gateway['DeviceUnderTestUserid']+'@'+gateway['DeviceUnderTestIP'],'password:']

相反,我最终得到了这个:

print vars['Valid_Login_Test_Vairables']['valid_ssh_command']

"ssh gateway['DeviceUnderTestUserid']@gateway['DeviceUnderTestIP']", 'password:'

我一直在尝试的是:

import varfile
import dummy.gateway
vars=varfile.get_variables(dummy.gateway)

我的 dummy.gateway 看起来像这样:

gateway['license_test_data'] = "gateway['license_test_data']"
gateway['license_for_application'] = "gateway['license_for_application']"
gateway['license_for_setup'] = "gateway['license_for_setup']"

如何将变量文件的确切内容转换为有用的数据结构?

4

1 回答 1

1

我发现你的问题有点难以理解,但如果我能正确地做到这一点,下面会从你所拥有的东西中产生你所说的你想要的东西。

# used as a stand-in for your 'import dummy.gateway'
dummy_gateway = {}
dummy_gateway['license_test_data'] = "gateway['license_test_data']"
dummy_gateway['license_for_application'] = "gateway['license_for_application']"
dummy_gateway['license_for_setup'] = "gateway['license_for_setup']"
dummy_gateway['DeviceUnderTestUserid'] = "gateway['DeviceUnderTestUserid']"
dummy_gateway['DeviceUnderTestIP'] = "gateway['DeviceUnderTestIP']"

# your example code corrected and reformatted to be slightly more readable
def get_variables(gateway):
    variables={
        'gateway':gateway,
        'license_test_data':gateway['license_test_data'],
        'license_for_application':gateway['license_for_application'],
        'Valid_Login_Test_Vairables':{
            'valid_ssh_command':
                ['ssh '+gateway['DeviceUnderTestUserid']+'@'+
                    gateway['DeviceUnderTestIP'],
                 'password:']
            }
        #around 3000 more just like this or worse
       }
    return variables

vars = get_variables(dummy_gateway)
print vars['Valid_Login_Test_Vairables']['valid_ssh_command']

结果,list由两个字符串组成:

["ssh gateway['DeviceUnderTestUserid']@gateway['DeviceUnderTestIP']",'password:']

希望这可以帮助。

PS BTW 该名称与标准库中的内置 Python 函数vars的名称冲突,因此将其用作其中一个变量的名称通常被认为是一种不好的编程习惯,即使这样做是有效的,就像在这种情况下一样顺其自然。

于 2011-12-02T21:33:02.907 回答