0

passing argeparse as us-east-1,us-east-2,us-east-3

# Setup commandline arguments
parser = argparse.ArgumentParser(description='using Terraform')
parser.add_argument(
    '-r',
    '--region',
    type=str,
    required=True,
    help='Region in which the ec2 need to be created')

and then trying to for loop for in each region

for region_1 in ([region]):
  print(region_1)

for print(region_1) its prininting all the regions but i want it iteration in loop and print one region at a time. please let me know whatcan be done

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
cad
  • 337
  • 2
  • 15

3 Answers3

2

This answer solves your question if you want to define better how the arguments should be passed.

For example, you should pass it like --region 'us-east-1' 'us-east-2' 'us-east-3'. And define your argument option using nargs like:

parser.add_argument(
    '-r',
    '--region', 
    nargs='+',
    type=str,
    required=True,
    help='Region in which the ec2 need to be created' 
)

In your case if you want to have a string separated by comma just do:

for r in region.split(","):
  print(r)
juanesarango
  • 560
  • 9
  • 17
2

You could do it by using nargs for the -r/--regions in argparse like,

$ cat arg.py 
import argparse

parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument(
    '-r',
    '--regions', 
    dest='regions',
    nargs='+',
    required=True,
    help='foo bar'
)

args = parser.parse_args()

for region in args.regions:
    print(region)

$ python arg.py -r us_east us_west us_east1
us_east
us_west
us_east1
han solo
  • 6,390
  • 1
  • 15
  • 19
0

You're iterating over a list that contains one element: region. [region] is a list containing region just like [1] is a list containing a 1.

Don't wrap that variable in another list before iterating it:

for region_1 in region:
Carcigenicate
  • 43,494
  • 9
  • 68
  • 117