Booster
Booster

Reputation: 11

How can I use sys and argparse in same python script without getting unrecognized argument error?

As my title suggests, I am using sys and argparse to add command line arguments to my code. Sys is being used to add a file path like /sample/test/etc and argparse is being used to add a separate optional functionality in my code. My code works just fine when I use just argparse but when sys comes in the picture is when the following error shows up:

test.py: error: unrecognized arguments: /sample/test/etc

The first few lines of my code I use sys to save the file path into a variable:

import sys

path = sys.argv[1]

Is there anyway I can utilize sys to record a file path while keeping my argparse which is, -r, later in the code?

Upvotes: 0

Views: 237

Answers (1)

teekarna
teekarna

Reputation: 1034

You do not need to use sys.argv to capture the path, you can handle both arguments with argparse. If you add an argument without a - prefix, it will be treated as a compulsory positional argument:

import argparse

parser = argparse.ArgumentParser(description='Description')
parser.add_argument('path', help='Path')
parser.add_argument('-r', '--relative', action='store_true',
                    help='optional argument')
args = parser.parse_args()
print('path: {:}'.format(args.path))
print('relative: {:}'.format(args.relative))

Usage:

myscript.py [-h] [-r] path

Upvotes: 1

Related Questions