1

My python code is as follows:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("--cmd_list", nargs="+")
args = parser.parse_args()
cmd_list = args.cmd_list
print(cmd_list)

I am aware of the fact that if I need to pass special characters as part of command line arguments, I need to enclose them within "" or ''.

As an example the following works [passing $ as an argument]:

python3 myfile.py --cmd_list 'sh' '$L'

But, encoding '-' within braces does not help.

As an example if I trigger the following:

python3 myfile.py --cmd_list 'sh' '-L'

I get the following error:

error: unrecognised arguments: -L

Is there a way to incorporate '-' as a program argument?

mang4521
  • 742
  • 6
  • 22
  • 1
    Or [How to parse positional arguments with leading minus sign (negative numbers) using argparse](https://stackoverflow.com/questions/14693718/how-to-parse-positional-arguments-with-leading-minus-sign-negative-numbers-usi) – Yevhen Kuzmovych Dec 09 '22 at 14:37

1 Answers1

-1

Use sys.argv to access arguments without processing them, let file.py content be

import sys
args = sys.argv[1:] # 1st element is file name
print(args)

then

python3 file.py --cmd_list 'sh' '-L'

gives output

['--cmd_list', 'sh', '-L']
Daweo
  • 31,313
  • 3
  • 12
  • 25
  • Yes this works but doesn't make use of *argparse* and also treats *--cmd_list* which ideally needs to be the key to an argument as an argument itself. – mang4521 Dec 09 '22 at 14:41