Python startup script [duplicate]

此生再无相见时 提交于 2019-12-22 07:05:47

问题


I would like to execute a script work.py in Python, after executing some initialization script init.py.

If I were looking for an interactive session, executing python -i init.py or setting PYTHONSTARTUP=/path/to/init.py would do the trick, but I am looking to execute another script.

Since this is a generic case which occurs often (init.py sets environment and so is the same all of the time), I would highly prefer not referencing init.py from work.py. How could this be done? Would anything change if I needed this from a script instead of from the prompt?

Thank you very much.


回答1:


More generally than in the accepted answer of C0deH4cker, this is discussed in the Python manual in Section 2.2.5 - Cusomization Modules. The basic idea is, to get the location of the special start-up script, one needs to execute the following Python code, e.g. from the interactive session of the interpreter:

>>> import site
>>> site.getusersitepackages()
'/home/user/.local/lib/python3.2/site-packages'

The output should be exactly such a location, in the file sitecustomize.py.




回答2:


Python has a special script that is run on startup. On my platform it is located at /usr/lib/python2.5/site-packages/sitecustomize.py IIRC. So, you could either put init.py in that directory alongside a sitecustomize.py script that imports it, or just paste the content of init.py in the sitecustomize.py.



来源:https://stackoverflow.com/questions/11404165/python-startup-script

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!