Using argparse, I have created a small script that contains a command line parser for my analysis program which is part of a self made python package. It works perfectly, but I don't really like how to control it.
This is how the code looks in the script itself
def myAnalysis():
parser = argparse.ArgumentParser(description='''
lala''')
parser.add_argument('-d', '--data',help='')
parser.add_argument('-e', '--option_1', help='', default=False, required=False)
parser.add_argument('-f', '--option_2', help='', default=False, required=False)
# combine parsed arguments
args = parser.parse_args()code here
Additional to this there is some more in the setup file of the analysis package
entry_points={
'console_scripts': [
'py_analysis = edit.__main__:myAnalysis'
]
As I said, this works without any problems. To analyze some data I have to use
py_analysis --data path_to_data_file
Sometimes, I need some of the options. For this it may look loke
py_analysis --data path_to_data_file --option_1 True --option_2 True
In my personal taste, this is kind of ugly. I would prefer something like
py_analysis path_to_data_file --option_1 --option_2
I am pretty sure this is possible. I just don't know how
Use store_true action
parser.add_argument('-e', '--option_1', help='', default=False, action ='store_true')
Then just adding to command line --option_1 will set its value to True .
To have a positional argument instead of an option, replace:
parser.add_argument('-d', '--data',help='')
by:
parser.add_argument('data_file', help='')
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.