2

我正在使用 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'
4

1 回答 1

3

在 Join 之前使用字符串连接:

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

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 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"]]}
于 2017-02-26T22:29:58.690 回答