Skip to content
Advertisement

How to parse a string in argparser during execution

I want to create a mini shell, so after i run my file,

python3 ./main.py

With whatever arguments I add, I then just constantly take input like a normal shell,

>> command
output
>> -s
output
>> ...

So I am just doing simple while True: command = input(), but these commands may take flags as well so stuff like

>> command -s -p -h

However I can’t really parse these the same way as when I run the the first file. Is there a way to parse the command -s -p -h part again into argparser so I get the nice namespace?

I basically want my program to argparse normally when I run the main.py in the first place then be able to parse strings I create in the script, x = input() again in with the same format for running my main.py.

Advertisement

Answer

.parse_args() can take an args argument with a list of strings to parse, for example:

import argparse

parser = argparse.ArgumentParser(add_help=False)
parser.add_argument('-s', action='store_true')
parser.add_argument('-p', action='store_false')
parser.add_argument('-h', action='store_true')

command = 'command -s -p -h'
command_name, *command_args = command.split()
command_args_parsed = parser.parse_args(args=command_args)
print(command_args_parsed)  # -> Namespace(h=True, p=False, s=True)

(The splitting here is just for example. You might be using something more thorough like shlex.split().)

This is covered in the documentation here: Parsing arguments

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement