Parsing a string using argparse

Question:

So I want the input of argparse to be a string instead of the command line.
for example:

python3 some_script.py arg1 arg2 arg3

I want to give the argparse the string "arg1 arg2 arg3"

import argparse
command = "arg1 arg2 arg3"
parser = argparse.ArgumentParser()
# add args here
args = parser.parse_args()
# process the command here and extract values

Asked By: Allonios

||

Answers:

You can use list directly in parse_args()

args = parser.parse_args(["arg1", "arg2", "arg3"])

or you can use your line

command = "arg1 arg2 arg3"
args = parser.parse_args(command.split(" "))

You can always put it in sys.argv and parser should use it

import sys

sys.argv = ["script", "arg1", "arg2", "arg3"]

it can be useful if you want to append() some option to values which you get from command line

sys.argv.append("--debug")

If you have more complex command with quoted strings like

'arg1 "Hello World" arg3' 

then you can use standard module shlex to split it correctly into three arguments

import shlex
shlex.split('arg1 "Hello world" arg3')


['arg1', 'Hello World', 'arg3']. 

Normal command.split(" ") would incorrectly give four arguments

['arg1', '"Hello', 'World"', 'arg3']
Answered By: furas
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.