Auto-load a module on python startup

时光总嘲笑我的痴心妄想 提交于 2019-11-27 14:25:09

Check the file ~/.ipython/ipythonrc - you can list all modules you want to load at the startup.

pyfunc

Have a .pythonstartup in your home directory and load modules there and point PYTHONSTARTUP env to that file.

Python commands in that file are executed before the first prompt is displayed in interactive mode.

I use it for enabling command line completion in python interpreter shell

Unless -S option is passed to the python binary, a special site module is imported by default before the execution is passed to your script, or the interactive interpreter. Among other things the module looks for *.pth files. On each line the *.pth files should contain either a path to include into sys.path, or a command to execute. The module as well imports sitecustomize, and usercustomize (which can contain arbitrary code, a good way to make your colleagues crazy, if they happen to raise errors) if they exist somewhere in sys.path.

The problem is though, that the current directory in not in sys.path when the site module is imported, that is it is hard to configure your particular script.

I sometimes add the following line at the beginning of my scripts, so that the script would start with searchin for .pth files in the current directory and adding the missing paths to sys.path:

# search for *.pth files in the current directory
import site; site.addsitedir('')

Another possible solution is to use the argument -i from python interpreter that launches the interaction mode after executing your script.

You could for instance use:

  • python -i your_module.py
  • python -i /path/to/your/module in case you have defined a __main__.py
  • or even python -i -m your.module
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!