if __name__ == '__main__' in IPython

前端 未结 4 692
情话喂你
情话喂你 2021-01-01 13:30

I have Python scripts that use the if __name__ == \'__main__\' trick to have some code only run when the script is called as a script and not when it is loaded

4条回答
  •  长发绾君心
    2021-01-01 13:55

    IPython adds the function get_ipython() to the globally available variables. So you can test, whether this function exist in globals() to make your decision:

    if __name__ == '__main__' and "get_ipython" not in dir():
        print "I'm not loaded with IPython"
    

    The above code just tests whether there is a global variable with name get_ipython. To also test whether this variable is callable, you can do:

    if __name__ == '__main__' and not callable(globals().get("get_ipython", None)):
        print "I'm not loaded with IPython"
    

提交回复
热议问题