Add a directory to Python sys.path so that it's included each time I use Python

StackOverflow https://stackoverflow.com/questions/7472436

  •  22-01-2021
  •  | 
  •  

سؤال

Currently, when trying to reference some library code, I'm doing this at the top of my python file:

import sys
sys.path.append('''C:\code\my-library''')
from my-library import my-library

Then, my-library will be part of sys.path for as long as the session is active. If I start a new file, I have to remember to include sys.path.append again.

I feel like there must be a much better way of doing this. How can I make my-library available to every python script on my windows machine without having to use sys.path.append each time?

هل كانت مفيدة؟

المحلول

Simply add this path to your PYTHONPATH environment variable. To do this, go to Control Panel / System / Advanced / Environment variable, and in the "User variables" sections, check if you already have PYTHONPATH. If yes, select it and click "Edit", if not, click "New" to add it.

Paths in PYTHONPATH should be separated with ";".

نصائح أخرى

If this is a library that you use throughout your code, you should install it as such. Package it up properly, and either install it in your site-packages directory - or, if it's specific to certain projects, use virtualenv and install it just within the relevant virtualenvs.

  1. You should use os.path.join to make your code more reliable.
  2. You have already used my-library in the path. So don't user it the second time in import. If you have a directory structure like this C:\code\my-library\lib.py and function in there, e.g.
  print("Hello, world")

then your resulting code should be

import sys 
sys.path.append(os.path.join('C:/', 'code', 'my-library')
from lib import main 

To do such a thing, you'll have to use a sitecustomize.py (or usercustomize.py) file where you'll do your sys.path modifications (source python docs).

Create the sitecustomize.py file into the \Lib\site-packages directory of your python installation, and it will be imported each time a python interpreter is launched.

If you are doing this interactively, the best thing to do would be to install ipython and configure your startup settings to include that code. If you intend to have it be part of a script you run from the interpreter, the same thing applies, since it will have access to your namespace.

On the other hand, a stand alone script should not include that automatically. In the future, you or some other maintainer will come along, and all the code should be obvious, and not dependent upon a specific machine setup. The best thing to do would be to set up a skeleton file for new projects that includes all of the basic functionality you need. That, along with oft-used snippets will handle the problem.

All of your code to run the script, will be in the script, and you won't have to think about adding that code every time.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top