Python startup script [duplicate]

2019-05-01 04:28发布

问题:

This question already has an answer here:

  • Passing options to Python executable in non-interactive mode 4 answers

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.