Search code examples
python-2.7moduleprogram-entry-point

Run a python script from another python script using IF __name__ == "__main__" statement


I have a script LCP_02.py with the if statement:

if __name__ == "__testcase__" or __name__ == "__main__":

    ask_costsurfacepath_path()
    ask_outputpath_path()
    CostSurfacefn = config.costsurfacepath
    startCoord = (config.startX,config.startY)
    stopCoord = (config.stopX,config.stopY)
    outputPathfn = config.outputpath
    main(CostSurfacefn,outputPathfn,startCoord,stopCoord)

when I run testcase.py (below) in the shell, it doesn't run the LCP_02 script:

import config
import LCP_02

if __name__ == "__main__":
    config.startX = 356254.432
    config.startY = 5325191.299
    config.stopX = 346200.101
    config.stopY = 5301688.499
    LCP_02

All the functions in LCP_02 have print statements (as a visual). But when running testcase.py, they are not printed. The program starts, waits around 2 seconds, and then shows the >>> in the shell.


Solution

  • There are two reasons it doesn't work:

    1. You imported LCP_02, so the __name__ value in that module is set to 'LCP_02', not '__main__' or '__testcase__'. The name is never based on whatever imported the module.

    2. Just referencing LCP_02 on a line won't 'invoke' that module; if the guarded code was going to run, it would have done so when importing.

    Use a function in LCP_02 instead:

    def run_test():
        ask_costsurfacepath_path()
        ask_outputpath_path()
        CostSurfacefn = config.costsurfacepath
        startCoord = (config.startX,config.startY)
        stopCoord = (config.stopX,config.stopY)
        outputPathfn = config.outputpath
        main(CostSurfacefn,outputPathfn,startCoord,stopCoord)
    
    if __name__ == "__main__":
        run_test()
    

    and call that function from your testcase.py module:

    LCP_02.run_test()