1

Using argparse module, is it possible to disable recognizing of regex expressions in command-line arguments?

For example, if I have a code such as

#!/usr/bin/python3

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("-a", "--arg", dest = "arg", nargs = 1, default = None)

args = parser.parse_args()

If someone runs this program as ./prog.py -a *, args.arg will be a list containing files in a present working directory, instead of a list containing just a '*', which is what I want.

So is there a way to disable this regex matching of argparse?

2 Answers 2

3

It's not related to argparse, regex nor to Python in general. It's your terminal doing shell expansion and it's happening even before the Python interpreter is executed.

You should use quotes, ie ./prog.py -a "*"

Sign up to request clarification or add additional context in comments.

Comments

0

This is not regular expression matching in Python, but your shell expanding * to a list of files matching that wildcard. This is the default behavior of shells in Unix-like systems (not on Windows where this is the responsibility of the program) and you cannot avoid this from your program. If you don't want the shell do do this, you need to quote the argument ("*") or escape it (\*).

Comments

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.