将特殊字符附加到 python 中的值

Append special character to a value in python

我正在尝试删除那些环境(实例)已终止的所有堆栈。将 stack_name 传递给 delete_stack 时会抛出错误。我曾尝试将特殊字符(如 '')添加到 stack_name 的值中,但没有成功。有人可以帮我解决这个问题吗?提前致谢!

#!/usr/bin/env python

import boto
import boto.ec2
import boto.cloudformation
import re
from datetime import datetime, timedelta

utclast = datetime.utcnow() - timedelta(2)

conn = boto.cloudformation.connect_to_region('us-west-1',aws_access_key_id = '<access_key>',aws_secret_access_key = '<secret_key>')
conn_ec2 = boto.ec2.connect_to_region('us-west-1',aws_access_key_id = '<access_key>',aws_secret_access_key = '<secret_key>')

stacks = conn.list_stacks()
for stackSumm in stacks:
    pattern = re.compile("Testupload-env([a-zA-Z0-9]+)")
    match = pattern.match(stackSumm.stack_name)
    if stackSumm.stack_status in "CREATE_COMPLETE" and match and stackSumm.stack_name in match.string:
        m = re.split(r'Testupload-', stackSumm.stack_name)
        instance = conn_ec2.get_all_instances(filters={"tag:Name": m[1]})
        if not instance:

            try:
                    print "Trying to delete stack: %s" % stackSumm.stack_name
                    conn.delete_stack(stackSumm.stack_name)

            except boto.exception.BotoServerError, e:
                    print e.error_message

错误:

File "delete_stack.py", line 7, in <module>
    conn.delete_stack(Testupload-envmeraleb8b01739116b0f36d17a2b5445b949f592bb625-6293)
NameError: name 'Testupload' is not defined

None 您发布的代码产生了错误,但 NameError 表示您没有提供有效的堆栈名称

delete_stack(stack_name_or_id) Deletes a specified stack. Once the call completes successfully, stack deletion starts. Deleted stacks do not show up in the DescribeStacks API if the deletion has been completed successfully.

Parameters: stack_name_or_id (string) – The name or the unique identifier associated with the stack.

name/id应该是字符串,python中的字符串必须用单引号或双引号引起来

stack_name = "Testupload-envmeraleb8b01739116b0f36d17a2b5445b949f592bb625-6293"
conn.delete_stack(stack_name)