【问题标题】:Python variable value in quotes引号中的 Python 变量值
【发布时间】:2012-04-11 21:52:17
【问题描述】:

我正在编辑一个脚本,该脚本对 openstack keystone 进行身份验证以获取令牌。 API-Call 有效,但我想使用变量而不是直接值来使其更具可读性和可重用性。但问题是值必须用引号 (") 括起来,我不知道该怎么做。我发现一些代码示例 [1]、[2] 通常在字符串中使用变量,但是我需要使用某种转义序列将值放在引号中。

目前我的字符串分配如下所示:

params = '{"auth":{"passwordCredentials":{"username":"nodermatt", "password":"feelfree"}, "tenantId":"4"}}'

如您所见,用户名、密码和租户 ID 的值都用引号引起来,我想用变量替换它们:

osuser = "nodermatt"
ospassword = "feelfree"
ostenant = "4"

params = '{"auth":{"passwordCredentials":{"username":osuser, "password":ospassword}, "tenantId":ostenant}}'

如果能解决这个“问题”,我会很高兴。

PS:如果我错过了与我的问题相匹配的 google 线程或搜索结果,我将非常感谢链接。

提前致谢! 最好的祝福, 尼古拉斯

[1]Subprocess in Python Add Variables

[2]http://ubuntuforums.org/showthread.php?t=786879

【问题讨论】:

    标签: python string variables variable-assignment quotes


    【解决方案1】:

    您是否尝试过使用格式字符串?

    params = '{"auth":{"passwordCredentials":{"username":%s, "password":%s}, "tenantId":%s}}' % (osuser, ospassword, ostenant)
    

    【讨论】:

      【解决方案2】:

      格式字符串就是您要查找的内容,如下所示:

      '{"username": "%s", "password":"%s"}' % (osuser, ospassword)
      

      如果您有很多变量要替换,您可能需要使用扩展的 语法:

      values = {'osuser': "nodermatt",
          'ospassword': "feelfree",
          'ostenant': 4}
      params =  '''{"auth":{"passwordCredentials":{"username":"%(osuser)s",
      "password":"%(ospassword)s"}, "tenantId":"%(ostenant)d"}}''' % values
      

      请注意,您可以简单地将引号放在模板字符串中您希望它们出现的位置。我以ostenant 为整数作为示例,但您也可以将其视为字符串(在字典和模板字符串中)。

      【讨论】:

        【解决方案3】:

        对于这种特殊情况,最简单的解决方案是先定义一个 Python 字典,然后使用json.dumps() 将其转换为 JSON:

        osuser = "nodermatt"
        ospassword = "feelfree"
        ostenant = "4"
        
        d = {"auth": 
                {"passwordCredentials": {"username": osuser, "password": ospassword},
                 "tenantId": ostenant}}
        params = json.dumps(d)
        

        【讨论】:

        • +1:用于连接 OP 实际上试图构建有效 json 字符串的点。
        【解决方案4】:

        这里有一个python库:https://github.com/openstack/python-keystoneclient

        它使用 Sven 建议的 JSON 编码。

        来自自述文件:

        # use v2.0 auth with http://example.com:5000/v2.0")
        >>> from keystoneclient.v2_0 import client
        >>> keystone = client.Client(username=USERNAME, password=PASSWORD, tenant_name=TENANT, auth_url=KEYSTONE_URL)
        >>> keystone.tenants.list()
        >>> tenant = keystone.tenants.create(name="test", descrption="My new tenant!", enabled=True)
        >>> tenant.delete()
        

        【讨论】:

          猜你喜欢
          • 2018-09-29
          • 2022-07-03
          • 2013-03-10
          • 2016-04-12
          • 2012-06-24
          • 1970-01-01
          • 2017-12-17
          • 2015-10-08
          • 1970-01-01
          相关资源
          最近更新 更多