snakehand
snakehand

Reputation: 39

Python pass external arguments and execute accordingly

python -size big The size is big.

python -size big -color blue The size is big. The color is blue.

Currently, I am splitting the arguments by delimiter of '-' then take 2nd item of the list and print if those conditions met. Is there any better ways to do so?

Upvotes: 0

Views: 323

Answers (2)

TayTay
TayTay

Reputation: 7170

There wasn't too much shared, but I think I see what you're after. You want to use argparse for this sort of thing:

# main.py
import argparse


if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description="Helpful description here",
    )

    parser.add_argument(
        "--size",
        type=str,
        dest="size",
        default="small",
        help="The size",
    )

    parser.add_argument(
        "--color",
        type=str,
        dest="color",
        default="green",
        help="The color",
    )

    args, unknown = parser.parse_known_args()
    if unknown:
        raise ValueError(f"Unknown args: {unknown}")

    print(f"Size is: {args.size}")
    print(f"Color is: {args.color}")

Here's a default call:

$ python main.py
Size is: small
Color is: green

Here's a call with only size provided:

$ python main.py --size gigantic
Size is: gigantic
Color is: green

Here's a call with both:

$ python main.py --size HUGE --color purple
Size is: HUGE
Color is: purple

And you can even get help:

$ python main.py --help
usage: main.py [-h] [--size SIZE] [--color COLOR]

Helpful description here

optional arguments:
  -h, --help     show this help message and exit
  --size SIZE    The size
  --color COLOR  The color

Upvotes: 2

Sudharsan Balajee
Sudharsan Balajee

Reputation: 56

You can make use of argparse which makes things simpler.

import argparse
parser = argparse.ArgumentParser()

# Add your arguments here
parser.add_argument("--color", "some desc")

args = parser.parse_args()

# Access the arguments 
print(args.color)

So your command to execute can have the arguments included like this

python test.py --color "blue"

Upvotes: 1

Related Questions