简体   繁体   中英

Argparse with action='store_true' not working as expected

The idea is to add a flag ( --slack , or -s ) when running the script, so that I don't have to comment out the rep.post_report_to_slack() method every time I don't want to use it. When I run:

$ python my_script.py --slack

I get the error:

my_script.py: error: unrecognized arguments: --slack

Here's the code:

def main():
    gc = Google_Connection()
    meetings = gc.meetings

    rep = Report(meetings)

    if args.slack:
        rep.post_report_to_slack()
        print('posted to slack')


if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('-s', '--slack', help='post to slack', 
        action='store_true')
    args = parser.parse_args()
    main()

Your code works, but it relies on args being available in the module namespace, which isn't great because, for one thing, it means you can't use your function without calling the script from the command line. A more flexible and conventional approach would be to write the function to accept whatever arguments it needs, and then pass everything you get from argparse to the function:

# imports should usually go at the top of the module
import argparse

def get_meeting_report(slack=False):

    gc = Google_Connection()
    meetings = gc.meetings

    rep = Report(meetings)

    if slack:
        rep.post_report_to_slack()
        print('posted to slack')

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('-s', '--slack', help='post to slack',
        action='store_true')
    args = parser.parse_args()
    args = vars(args)
    get_meeting_report(**args)

Now you can also more easily use your function outside of argparse by calling it directly.

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