In the script I'm writing, I am using argparse for the main arguments (for --help, --todo, etc.) but trying to use sys.argv to get the name of a file given as the third argument for --add. I was using this:
def parseargs():
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument("--help", help="Print argument usage", action="store_true")
parser.add_argument("--memo", help="Read memo file", action="store_true")
parser.add_argument("--todo", help="Read TODO file", action="store_true")
parser.add_argument("--trackedfiles", help="Read tracked files list", action="store_true")
parser.add_argument("--add", help="Add a file to trackedfiles", action="store_true")
parser.add_argument("--edit", help="Edit file in .wpm_data with editor", action="store_true")
parser.add_argument("--newdir", help="Create a new directory to initialize user-data", action="store_true")
parser.add_argument("file")
p_args = parser.parse_args()
if p_args.help:
printargs()
sys.exit()
if p_args.memo:
print_memo()
sys.exit()
if p_args.todo:
print_todo()
sys.exit()
if p_args.trackedfiles:
print_trackedfiles()
sys.exit()
if p_args.add: # this is were I'm stumpped
if p_args.file == sys.argv[2]:
givenfile = p_args.file
else:
pass
print("[!]\t", givenfile, "to be added to trackedfiles")
sys.exit()
Which works like this:
./main.py --add textfile.txt
[!] textfile.txt to be added to trackedfiles
But when a different argument would be used like --help
, a third argument needs to be used for givenfile
./main.py --help
usage: main.py [--help] [--memo] [--todo] [--trackedfiles] [--add] [--edit]
[--newdir]
file
main.py: error: the following arguments are required: file
How can I separate using argparse and sys.argv, with sys.argv not constantly needing to be used so it can only be called when a function that needs it is run?