Ваша проблема на самом деле не в функции print, а в том, как вы выполняете циклы for.Я комментировал ваш код ниже, добавил подсказку, чтобы сэкономить ваше время, и включил некоторый код, чтобы преодолеть это препятствие. Здесь - это ресурс для циклов, а здесь - другой ресурс для использования списков.
Вот ваш код с аннотациями того, чтопроисходит:
#import libraries, prepare the data
import boto3
from boto3.dynamodb.conditions import Key, Attr
dynamo = boto3.resource('dynamodb')
table = dynamo.Table('mytable')
s3.Bucket('instances').download_file('MissingInstances.txt')
#Opens the text file that has the name of an instance and a newline character per line
with open('MissingInstances.txt', 'r') as f:
#For each line in the text file
for line in f:
#(For each line) Create an empty list called missing_instances
missing_instances = []
#Append this line to the empty list
missing_instances.append(line)
#Put all the current values of the list into a space-delimited string
#(There is only one value because you have been overwriting the list every loop)
unscanned = ''.join(missing_instances)
На этом этапе кода вы перебрали и записали missing_instances
каждую итерацию вашего цикла, поэтому у вас остался только последний экземпляр.
#This should print the whole list of missing_instances
>>>print(*missing_instances)
i-cccccc
#This should print the whole unscanned string
>>>print(unscanned)
i-cccccc
Далее вы перебираете без сканирования:
#For each letter in the string unscanned
for i in unscanned:
#Print the letter
print(i)
#Query using the letter (The rest of this won't work for obvious reasons)
response = table.query(KeyConditionExpression=Key('EC2').eq(i))
items = response['Items']
print(items)
Вам не нужно присоединяться к списку для преобразования в строку
У меня есть скрипт, который добавляет список в текстовый файл.Затем я использую '' .join (mylist) для преобразования в тип str, чтобы я мог запросить у таблицы DynamoDB указанную строку str
Например:
Если у вас есть этот список:
missing_instances = ['i-xxxxxx','i-yyyyyy','i-zzzzzz']
Вы можете видеть, что его тип данных list
:
>>>print(type(missing_instances))
<class 'list'>
Но если вы смотрите на элемент этого списка (например, первыйelement), тип данных элемента: str
:
>>>print(type(missing_instances[0]))
<class 'str'>
Этот код перебирает текстовый файл и запрашивает каждую строку в базе данных:
#import libraries, prepare the data
import boto3
from boto3.dynamodb.conditions import Key, Attr
dynamo = boto3.resource('dynamodb')
table = dynamo.Table('mytable')
s3.Bucket('instances').download_file('MissingInstances.txt')
#Open the text file
with open('MissingInstances.txt', 'r') as f:
#Create a new list
missing_instances = []
#Loop through lines in the text file
for line in f:
#Append each line to the missing_instances list, removing the newlines
missing_instances.append(line.rstrip())
#CHECKS
#Print the whole list of missing_instances, each element on a new line
print(*missing_instances, sep='\n')
#Print the data type of missing_instances
print(type(missing_instances))
#Print the data type of the first element of missing_instances
print(type(missing_instances[0]))
#Loop through the list missing_instances
#For each string element of missing_instances
for i in missing_instances:
#Print the element
print(i)
#Query the element
response = table.query(KeyConditionExpression=Key('EC2').eq(i))
#Save the response
items = response['Items']
#Print the response
print(items)
#For good measure, close the text file
f.close()