简体   繁体   中英

Passing arguments to a Python script

I want to pass arguments to a Python script in two ways,

python main.py --source=aws

and

python main.py source aws

This is my current code,

parser = argparse.ArgumentParser()
parser.add_argument("--s", "--source", help='Flag to choose source')

This makes the first option possible. How do I make the second option possible?

There is not a way to do that with Argparse. The only way to do that is by filtering stdin using sys.argv.

import argparse
import sys

mangle_my_args = ['s', 'source']
arguments=['--'+arg if arg in mangle_my_args else arg for arg in sys.argv[1:]]
parser = argparse.ArgumentParser()
parser.add_argument("--s", "--source", help='Flag to choose source')
print(parser.parse_args(arguments))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM