2

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
1
  • 1
    thanks it worked, using parser.parse_args( ["script", "arg1", "arg2", "arg3"] ) did exactly what I wanted. it was mantioned here all along docs.python.org/3.8/library/… Commented May 3, 2021 at 12:23

1 Answer 1

5

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

2 Comments

I often write my argparse setup functions with a signature like def _parse_args(args=sys.argv[1:]) to make it easier to test them, then I can just provide the test args when calling the function instead of having to modify sys.argv manually during testing.
yes, this is also useful method for test :) Documentation for ArgumentParser.parse_args shows that it gets None as default and then it uses sys.argv automatically - so you could even do def _parse_args(args=None)

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.