【问题标题】:Use environmental variables in between strings?在字符串之间使用环境变量?
【发布时间】:2021-03-22 08:55:41
【问题描述】:

我有一个字符串

start = """<?xml version="1.0" encoding="utf-8" ?><soap:Envelope \
         xmlns="http://tempuri.org/"> \
                    <UserName>username</UserName><Password>password</Password>\
                    xmlns="http://tempuri.org/"><oShipData>"""

我想为用户名和密码使用环境变量,而不是在代码中硬编码,我尝试了这个

import os
start = """<?xml version="1.0" encoding="utf-8" ?><soap:Envelope \
         xmlns="http://tempuri.org/"> \
                    <UserName>"""os.environ["username"]"""</UserName><Password>"""os.environ["password"]"""</Password>
                    xmlns="http://tempuri.org/"><oShipData>"""

但这给了我一个错误:

"errorMessage": "Syntax error in module 'test': invalid syntax (test.py, line 5)",
    "errorType": "Runtime.UserCodeSyntaxError"

如何转义字符串并从字符串中的os.environ 动态获取值?

【问题讨论】:

  • 只要在两边加上+就可以了。有很多方法可以达到所需的结果,看看str.format()。您的数据是 XML 格式的,所以最好使用xml.etree 来构建 XML 对象。
  • 这能回答你的问题吗? Multiline f-string in Python
  • @RandomDavis ,我尝试在我的代码中使用类似 f"house_bill_nbr = '{house_bill_nbr}'" 的格式,但由于这是 XML,它不接受这种格式

标签: python python-3.x string environment-variables string-formatting


【解决方案1】:

您可以在 python 中将字符串添加在一起。所以"teststring"是一个普通的字符串,但是"test"+variable+"string"会产生一个中间有变量值的字符串,假设变量是字符串类型。如果没有,请使用"test"+str(variable)+"string"

import os
start = """<?xml version="1.0" encoding="utf-8" ?><soap:Envelope \
         xmlns="http://tempuri.org/"> \
                    <UserName>"""+str(os.environ["username"])+"""</UserName><Password>"""+str(os.environ["password"])+"""</Password>
                    xmlns="http://tempuri.org/"><oShipData>"""

应该可以。

【讨论】:

    【解决方案2】:

    您不能只是将字符串和代码放在另一个旁边,您可以使用+ 连接它们

    start = """
    <?xml version="1.0" encoding="utf-8" ?>
        <soap:Envelope xmlns="http://tempuri.org/"> 
            <UserName>""" + os.environ["username"] + """</UserName>
            <Password>""" + os.environ["password"] + """</Password>
        <oShipData>"""
    

    【讨论】:

    • 第一行留空
    • 为避免第一行为空,请在start = """ 行的末尾添加一个反斜杠。
    【解决方案3】:

    你可以使用 f-strings:

    import os
    start = f"""<?xml version="1.0" encoding="utf-8" ?><soap:Envelope \
             xmlns="http://tempuri.org/"> \
                        <UserName>{os.environ['username']}</UserName><Password>{os.environ['password']}</Password>
                        xmlns="http://tempuri.org/"><oShipData>"""
    

    【讨论】:

      【解决方案4】:

      如果您打算使用 XML 对象,最好使用一些生成 XML 文档的类。在python中有内置的xml.etree.ElementTree

      代码:

      import os
      import xml.etree.ElementTree as ET
      
      envelope = ET.Element("soap:Envelope", attrib={"xmlns": "http://tempuri.org/"})
      username = ET.SubElement(envelope, "UserName")
      username.text = os.environ["username"]
      password = ET.SubElement(envelope, "Password")
      password.text = os.environ["password"]
      
      start = ET.tostring(envelope, encoding="utf-8", xml_declaration=True).decode()
      

      结果:

      <?xml version='1.0' encoding='utf-8'?>
      <soap:Envelope xmlns="http://tempuri.org/"><UserName>user</UserName><Password>pass</Password></soap:Envelope>
      

      附:在 python 3.9+ 上,您可以使用ET.indent(envelope) 获得漂亮的打印结果(在ET.tostring() 调用之前插入此内容)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-08-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-27
        相关资源
        最近更新 更多