user10205566
user10205566

Reputation:

get the list of values outside of loop-Python

I want to get variable output a (which is in loop), outside of loop

        stopped_reasons = []
        output=[]




         client = boto3.client('ec2')
         reservations = client.describe_instances().get('Reservations', []) 

         for reservation in reservations:
             for instance in reservation['Instances']:
               tags = {}
               for tag in instance['Tags']:

                    tags[tag['Key']] = tag['Value']
                    if tag['Key'] == 'Name':
                      name=tag['Value']     
             if instance['State']['Name'] == 'stopped':

                 instance_ids.append(instance['InstanceId'])
                 instance_names.append(name)
                 stopped_reason = instance['StateTransitionReason']
                 stopped_reasons.append(stopped_reason)
                 transition_timestamp = datetime.strptime(instance['StateTransitionReason'][16:39], '%Y-%m-%d %H:%M:%S %Z')
                 #print (datetime.now() - transition_timestamp).days
                 a="Instance:"+ instance['InstanceId']  + '  Name: ' +name + "TIME: "+str(transition_timestamp)
                 print a
                 output.append(a)

print output 

print a (inside loop) gives what i want:

Instance:i-03666a1aea6028cf0  Name: aws-opsworks-cm-instance-mypuppet-1541455366196TIME: 2018-11-15 18:30:27
Instance:i-0a67100fa09eab573  Name: Choco_ServerTIME: 2018-11-29 18:30:27

I'm trying to get same output but outside for loop. so i declared list output and appended a variable

but print output (outside loop) gives one line

['Instance:i-03666a1aea6028cf0  Name: aws-opsworks-cm-instance-mypuppet-1541455366196 TIME: 2018-11-15 18:30:27', 'Instance:i-0a67100fa09eab573  Name: Choco_Server TIME: 2018-11-29 18:30:27']

Upvotes: 0

Views: 2048

Answers (2)

user10205566
user10205566

Reputation:

just found it, have to join new line to the list

 body= "\n".join(output)
 print body

Upvotes: 2

Green Cloak Guy
Green Cloak Guy

Reputation: 24691

Notice that you're using output.append(a) - output is a list. In general python prints lists like you see there: all in one line, with brackets, and with quotes around strings.

If you want to print each of the lines separately without the quotes, then you have to print each element of the list individually, rather than printing the whole list at once. Instead of

print output

do

for line in output:
    print line

Upvotes: 0

Related Questions