Launch Python debugger while simultaneously executing module as script

前端 未结 5 1435
你的背包
你的背包 2020-12-14 09:21

When developing a Python package, it\'s very convenient to use the -m option to run modules inside the package as scripts for quick testing. For example, for

5条回答
  •  情话喂你
    2020-12-14 09:51

    Here's another option that also works with command line arguments.

    It's generally a good idea to wrap your script's logic in a main function. You can then have main take in an optional list of arguments to override sys.argv. Here's an example called argdemo.py:

    def main(cmd_line_args=None):
        import argparse
    
        parser = argparse.ArgumentParser()
        parser.add_argument("number", help="a number", type=int)
    
        # allow cmd_line_args to override sys.argv
        if cmd_line_args is None:
            args = parser.parse_args()
        else:
            args = parser.parse_args(cmd_line_args)
    
        print("The number is {}".format(args.number))
    
    if __name__ == '__main__':
        main()
    

    This module can be run as usual:

    $ python -m argdemo 2
    > The number is 2
    

    Or it can be run with pdb by calling main() directly:

    $ python -c "import pdb; import argdemo; pdb.runcall(argdemo.main, ['2'])"
    (Pdb) continue
    > The number is 2
    

    (Notice that cmd_line_args has to be a list of strings just like argv would be).

    As an added bonus, when your module has an import-able main function, you can write unit tests for it in the same way =)

提交回复
热议问题