I am trying to write a daemon service, which can be controlled in the command line. For example, to start the service
python3 test.py -c start -d /mydownloadfolder/ -j /myconfig.json
to stop the service,
python3 test.py -c stop
The -d
-j
parameters are required only when I start the service. Therefore, I need to implement conditionally required arguments based on the value of another argument.
I did some search and found this useful post Python Argparse conditionally required arguments The difference is: instead of checking the existence of '--command', I need to check the value of the '--command'.
Here is my tentative solution:
PARSER.add_argument('-c', '--command', required=True, help='provide a valid command: start, stop, restart, or status')
NEED_MORE_ARGS = PARSER.parse_args().command.lower().startswith('start')
PARSER.add_argument('-d', '--download', required=NEED_MORE_ARGS , default=LOCAL_DOWNLOAD, help='set account download folder')
PARSER.add_argument('-j', '--input', required=NEED_MORE_ARGS, default=JSON_INPUT, help='set input json file')
I parsed the args in the middle to get NEED_MORE_ARGS(boolean), and then add other args. The code seems not clean. Is there a better way to do this?
==============
Updated: The tentative solution does not work. :(