How to reorganize a script that uses the argparse argument to be called inside another Python script?

I have a script that finds test names and is widely used in our company. It works on the command line as follows:

find_test.py --type <type> --name <testname>

Inside the script there is an equivalent:

import argparse

parser = argparse.ArgumentParser(description='Get Test Path')
parser.add_argument('--type',      dest='TYPE',      type=str,            default=None,  help="TYPE [REQUIRED]")
parser.add_argument('--name',      dest='test_name', type=str,            default=None,  help="Test Name (Slow)")
parser.add_argument('--id',        dest='test_id',   type=str,            default=None,  help="Test ID (Fast)")
parser.add_argument('--normalise', dest='normalise', action="store_true", default=False, help="Replace '/' with '.' in Test Name")
args = parser.parse_args()

(Not sure what all these arguments are doing, I personally use only the first two). These lines are then processed by code that uses these arguments.

I want to reorganize this script so that I can import it as a module, but also keep its functionality on the command line, as many people use this script, and it is also called in some of our csh scripts.

I have edited it so far, for example:

def _main():
    <all the former code that was in find_test.py>

if __name__ == "__main__":
    _main()

. , script .

, script? ?

docopts, , argparse, , .. argparse, , .

+4
1

; .

, , , . ( , _.) , - - __name__ == '__main__', main().

:

def main(TYPE, test_name, test_id=None, normalise=False):
    # ... body of script...

if __name__ == "__main__":
    parser = ...
    ...
    args = parser.parse_args()
    main(**vars(args))

( docopt - , , .)

+3

Source: https://habr.com/ru/post/1666353/


All Articles