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

时间:2017-02-26 22:10:18

标签: python string join troposphere

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

1 个答案:

答案 0 :(得分:2)

在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 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"]]}