使用包含的变量重新格式化字符串

时间:2011-12-02 19:02:41

标签: python variables robotframework

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

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']"

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

1 个答案:

答案 0 :(得分: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:']

希望这有帮助。

P.S。 BTW名称vars与标准库中built-in Python function的名称冲突,因此将其用作其中一个变量的名称通常被认为是一种糟糕的编程习惯,即使这样做有效,如就这种情况而言。