2

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?

2
  • 4
    What is the benefit of providing both ways? There's no clean, simple way to support both. Commented Aug 20, 2019 at 20:08
  • 1
    The current code also allows: python main.py --source aws. Commented Aug 20, 2019 at 20:13

1 Answer 1

2

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))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.