Python troposphere: 如何合并包含 Join 的两个字符串

Python troposphere: How to combine two strings containing Join

我正在使用 troposhere 库,我正在尝试组合两个具有 Join 的字符串对象:

from troposphere import Join

str1 = Join('', ["""
sed -i -e '/hostname/s/=.*/=example.com/' /tmp/file.app
\n"""])

str2 = Join('', ["""
sed -i -e '/IP/s/=.*/=192.168.100.100/' /tmp/file.app
\n"""])

我尝试使用以下方法组合它们:

str3 = str1 + str2
and
str1 += str2

但不幸的是我收到以下错误:

TypeError: unsupported operand type(s) for +: 'Join' and 'Join'

在加入之前使用字符串连接:

您可以在创建联接之前应用字符串连接:

from troposphere import Join

str1 = """
sed -i -e '/hostname/s/=.*/=example.com/' /tmp/file.app
\n"""

str2 = """
sed -i -e '/IP/s/=.*/=192.168.100.100/' /tmp/file.app
\n"""

str3 = str1.strip()+str2

join1, join2, join3 = [Join('', [cmd]) for cmd in (str1, str2, str3)]

print join3.data
# {'Fn::Join': ['', ["sed -i -e '/hostname/s/=.*/=example.com/' /tmp/file.app\nsed -i -e '/IP/s/=.*/=192.168.100.100/' /tmp/file.app\n\n"]]}

定义连接加法:

这里是 Join class 的定义:

class Join(AWSHelperFn):
    def __init__(self, delimiter, values):
        validate_delimiter(delimiter)
        self.data = {'Fn::Join': [delimiter, values]}

要定义 join_a + join_b,您可以使用:

from troposphere import Join


def add_joins(join_a, join_b):
    delimiter = join_a.data['Fn::Join'][0]
    str_a = join_a.data['Fn::Join'][1][0]
    str_b = join_b.data['Fn::Join'][1][0]

    return Join(delimiter, [str_a.strip() + str_b])

Join.__add__ = add_joins

str1 = """
sed -i -e '/hostname/s/=.*/=example.com/' /tmp/file.app
\n"""

str2 = """
sed -i -e '/IP/s/=.*/=192.168.100.100/' /tmp/file.app
\n"""

join1 = Join('', [str1])
join2 = Join('', [str2])

print (join1 + join2).data
# {'Fn::Join': ['', ["sed -i -e '/hostname/s/=.*/=example.com/' /tmp/file.app\nsed -i -e '/IP/s/=.*/=192.168.100.100/' /tmp/file.app\n\n"]]}