简体   繁体   中英

Command line argument processing

How does one structure their command line processing block in such a way as to allow naming multiple files in any order AND to discover those file types by their suffixes?

In this Python program, I need to pass both a binary file and a .vhdr file to my command line. The .vhdr file will be read to memory, while the (large) binary file will be processed incrementally. I would like to build this in a way such that the user can pass the file names in any order. It seems to me that an intelligent way to deal with this would be to iterate over each item in argv, check if it has a ".vhdr" suffix, and use whichever item has this to save to my file object.

Do any libraries have this functionality, or should I write this from scratch? I was not able to find something like this in the argparse library, but I am new so I easily could have looked right at it and not understood.

Use well known argparse library. Simple example

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--vhdr", dest="vhdr_file")
parser.add_argument("--bin", dest="bin_file")
args = parser.parse_args()
print(args)

output:

$ python demo.py --vhdr 1 --bin 2
Namespace(bin_file='2', vhdr_file='1')
$ python demo.py  --bin 1 --vhdr 2
Namespace(bin_file='1', vhdr_file='2')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM