首页 > 解决方案 > 来自 AWS 的 Python Json 输出未删除单引号

问题描述

我对 Python 有点陌生,并且在玩各种类。我创建了一个类来访问 aws ec2 实例以随着当前状态停止和启动。除了显示问题之外,不知道如何解释这一点。

#!/usr/bin/python
import boto3
import json
import datetime
from botocore.exceptions import ClientError

class Ec2(object):
    def __init__(self, instance_id, region):
        self.instances = [instance_id]
        self.region = 'us-gov-west-1'
        self.state = ''

        if region is not None:
            self.region = region
        self.ec2 = boto3.client('ec2', region_name=region)
        self._setState()

    def _setState(self):
        def convert_timestamp(datetime_key):
            if isinstance(datetime_key, (datetime.date, datetime.datetime)):
                return datetime_key.timestamp()

        status = self.ec2.describe_instances(InstanceIds=self.instances)

        # Find the current status of the instance
        dump = json.dumps(status, default=convert_timestamp)
        body = json.loads(dump)
        self.state = body["Reservations"][0]["Instances"][0]["State"]["Name"]


    def getState(self):
        self._setState()
        return self.state
    ...

因此,如果在 Python3 解释器中运行以下命令:

from ec2 import Ec2
ssm_1 = Ec2('i-12345abcdef','us-gov-west-1')
ssm_1.getState()
Python 3.8.0 (default, Oct 28 2019, 16:14:01)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from ec2 import Ec2
>>> ssm_1 = Ec2('i-12345abcdef','us-gov-west-1')
>>> ssm_1.getState()
'stopped'
>>>

如果我将类中的方法 _setState 更改为:

def _setState(self):
        def convert_timestamp(datetime_key):
            if isinstance(datetime_key, (datetime.date, datetime.datetime)):
                return datetime_key.timestamp()

        status = self.ec2.describe_instances(InstanceIds=self.instances)

        # Find the current status of the instance
        dump = json.dumps(status, default=convert_timestamp)
        body = json.loads(dump)
        self.state = body["Reservations"][0]["Instances"][0]["State"]["Name"]
        self.state = self.state.replace("'", "")

然后重新运行上面的单引号不要被删除!这些引号似乎不是实际字符串的一部分,通过将最后一行更改为:

        self.state = self.state[1:-1]

>>> ssm_1.getState()
'toppe'

所以它删除了第一个和最后一个字母而不是单引号,s & d

但是,如果我将 _setState 更改为:

    def _setState(self):
        def convert_timestamp(datetime_key):
            if isinstance(datetime_key, (datetime.date, datetime.datetime)):
                return datetime_key.timestamp()

        status = self.ec2.describe_instances(InstanceIds=self.instances)

        # Find the current status of the instance
        dump = json.dumps(status, default=convert_timestamp)
        body = json.loads(dump)
        self.state = body["Reservations"][0]["Instances"][0]["State"]["Name"]

现在运行:

>>> from ec2 import Ec2
>>> ssm_1 = Ec2('i-12345abcdef','us-gov-west-1')
>>> ssm_1.getState().replace("'", "")
stopped
>>>

单引号现在不见了!

所以它出现在类中,字符串实际上并不包含单引号,而是在类之外。为什么?提前致谢。

标签: pythonamazon-web-servicesamazon-ec2replaceboto3

解决方案


推荐阅读