Utkarsh Sharma
Utkarsh Sharma

Reputation: 339

Can 'argparse' consume a string instead of python script arguments?

I have a string and I need to extract the positional params and optional params from it.

"start command test --param_1 a --param_2 b"

Is there a way we can extract the params from a string instead of script arguments using 'argparse' module?

Thanks

Upvotes: 1

Views: 485

Answers (1)

SethMMorton
SethMMorton

Reputation: 48875

argparse.parse_args() can accept a list to parse.

import argparse
parser = argparse.ArgumentParser()
# Insert your rules

# Parse my string, first splitting it into a list.
args = parser.parse_args("start command test --param_1 a --param_2 b".split())

If you need to be careful about quotes in your string, shelx.split may be better than .split().

Upvotes: 3

Related Questions