python - 来自 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
>>>
单引号现在不见了!
所以它出现在类中,字符串实际上并不包含单引号,而是在类之外。为什么?提前致谢。
解决方案
推荐阅读
- javascript - 通过从同一页面内的链接调用其锚 id 来扩展手风琴?
- mysql - MySQL XDevAPI 如何返回成功状态
- sql-server - 使用 SSRS MAX 函数时消除一些大值
- java - 如何从 2 个不同的 Spring Boot 应用程序访问相同的数据库
- reactjs - Apollo-Client 中的 dotenv 不起作用
- python - 在 Python 3.7/Django 3 中,如何在 Web 浏览器中获取页面的呈现 HTML?
- c# - 执行此 sql 查询时如何只获得一个值?
- r - 如何在 rmarkdown 代码块中解析文本表
- javascript - 如何使用引导程序使表格内的单选按钮看起来像一个按钮?
- flutter - 将分隔符添加到 ListTile