jeudi 16 juin 2016

Passing optional argument in python

I am trying to append a url by passing the parameters by commandline argument. Here is how I am trying:

import argparse
parser = argparse.ArgumentParser(description='Arguments')
parser.add_argument('input', metavar='input', type=str)
parser.add_argument('output', metavar='text', type=str)
args = parser.parse_args()
url = 'https://example.com/?z=12&text='+args.output+'&loc{}'
print url

When I execute

python url.py text.csv hello

It appends the second passed argument to the url. I want to know how to make the second argument optional so that even without providing the second argument I want the url to be printed by concatenating nothing to the url. Here is the output I am expecting:

When both arguments given:

python url.py text.csv hello

The output should be

https://example.com/?z=12&text=hello&loc{}

When single argument given

python url.py text.csv

The output should be

https://example.com/?z=12&text=&loc{}

Aucun commentaire:

Enregistrer un commentaire