Home > Back-end >  List S3 buckets and output them using inquier
List S3 buckets and output them using inquier

Time:10-29

I'm trying to list buckets with the option to select one of the buckets to upload a file using CLI.

the output of that code is always "Which buckets you want to choose" and 1 bucket name at the time before I hit enter, then it lists "which bucket.." and new bucket. I need a list and the way to select one of them to run put an object on that bucket.

My Code:

        s3 = boto3.client('s3')
        response = s3.list_buckets()
        # Output the bucket names
        print('Existing buckets:')
        for bucket in response['Buckets']:
            # print(f'  {bucket["Name"]}')
            questions = [
            inquirer.List('Buckets',
                        message="Which bucket you would like to upload file? \n",
                        choices=[{bucket["Name"]}],
                    ),
        ]
            answers = inquirer.prompt(questions)

CodePudding user response:

Look at your code closely. You display the prompt every single iteration, once for each bucket.

Instead, you should pre-build the list of available buckets and only then display the prompt:

s3 = boto3.client('s3')
response = s3.list_buckets()
list_of_buckets = [bucket["Name"] for bucket in response['Buckets']]
questions = [
    inquirer.List('Buckets',
                  message="Which bucket you would like to upload file? \n",
                  choices=list_of_buckets)
]
answers = inquirer.prompt(questions)
  • Related