Search code examples
pythonworkflowcommand-line-argumentscompiler-flags

Execute python solvers from another python script using flag variables


I'm currently working on a python pipline where I need to call different solvers/scripts from a python code and execute them. Since there would be different kind of codes involved, I would like to call these solvers based on flag parameters and run them accordingly. Below is an example of what I intend to do:

So there are two or more python codes, typically with 100s of lines of code, but here I have taken a generic example

#script1.py
import numpy
        
def test1():
    print('This is script One')


if __name__ == '__main__':
    test1()
#script2.py
import numpy
        
def test2():
    print('This is script two')


if __name__ == '__main__':
    test2()

At the moment I execute them from another script main.py with

#main.py
import numpy
from script1 import *
from script2 import *
    
if __name__=='__main__':
    test1()
    test2()

This main.py executes both of them which I don't want. I would like to use flag variables and execute them whichever I need to. Can this be done using argparse command line parsing ? As there might be further flags in each script.py for it to run. That would be something I prefer as well.

Thanks


Solution

  • You can do something like:

    #main.py
    import numpy
    import sys
    from script1 import test1
    from script2 import test2
        
    if __name__=='__main__':
        # sys.argv[0] is the executable so we skip it.
        for arg in sys.argv[1:]   
            if arg == "test1": 
                test1()
            elif arg == "test2": 
                test2()
    

    Now you can execute your tests as

    python main.py test1
    
    python main.py test2
    
    # or if you want to repeat a test several times or run multiple tests
    
    # will execute test1, then test2 then test1 again
    python main.py test1 test2 test1