Is there any way to instruct argparse (Python 2.7) to remove found arguments from sys.argv?

后端 未结 1 1469
死守一世寂寞
死守一世寂寞 2021-01-19 09:47

I\'m fully midstream in the development process for what is turning into a fairly substantial Python 2.7 project. Right now I have all of my unittest classes lumped togethe

相关标签:
1条回答
  • 2021-01-19 10:28

    You want parse_known_args()

    from __future__ import print_function
    import argparse
    import sys
    
    def main():
        print(sys.argv)
    
    
    if __name__ == "__main__":
        parser = argparse.ArgumentParser()
    
        parser.add_argument('--all', action='store_true')
        parser.add_argument('--utils_base', action='store_true')
    
        args, left = parser.parse_known_args()
    
        sys.argv = sys.argv[:1]+left
    
        main()
    

    Although, I must ask. Why are you writing your own test runner? The unittest module allows you to run specific sets of tests from the cli:

    # run test from a spefiic class
    $ python -m unittest module.tests.group.TestSpecific
    # all possible options
    $ python -m unittest --help
    Usage: python -m unittest [options] [tests]
    
    Options:
      -h, --help       Show this message
      -v, --verbose    Verbose output
      -q, --quiet      Minimal output
      -f, --failfast   Stop on first failure
      -c, --catch      Catch control-C and display results
      -b, --buffer     Buffer stdout and stderr during test runs
    
    Examples:
      python -m unittest test_module               - run tests from test_module
      python -m unittest module.TestClass          - run tests from module.TestClass
      python -m unittest module.Class.test_method  - run specified test method
    
    [tests] can be a list of any number of test modules, classes and test
    methods.
    
    Alternative Usage: python -m unittest discover [options]
    
    Options:
      -v, --verbose    Verbose output
      -f, --failfast   Stop on first failure
      -c, --catch      Catch control-C and display results
      -b, --buffer     Buffer stdout and stderr during test runs
      -s directory     Directory to start discovery ('.' default)
      -p pattern       Pattern to match test files ('test*.py' default)
      -t directory     Top level directory of project (default to
                       start directory)
    
    For test discovery all test modules must be importable from the top
    level directory of the project.
    

    If you need even more flexibility in grouping and running tests, I'd suggest looking at nosetest

    0 讨论(0)
提交回复
热议问题