How to make my Python module available system wide

2019-01-11 14:58发布

I made myself a little module which I happen to use quite a lot. Whenever I need it I simply copy it to the folder in which I want to use it. Since I am lazy I wanted to install it so that I can call it from anywhere, even the interactive prompt. So I read a bit about installing here, and concluded I needed to copy the file over to /usr/local/lib/python2.7/site-packages. That however, doesn't seem to do anything.

Does anybody know where I need to copy my module for it to work system wide?

5条回答
时光不老,我们不散
2楼-- · 2019-01-11 15:39

There are methods to install Python modules system-wide. You may want to take a look at distutils. A good tutorial for distutils2 (the current version) can be found here.

You basically have to write a file setup.py which tells distutils what to do. Then you can simply

python setup.py install

with root permissions to install your module systemwide. There are good and easy examples, plus it's the cleanest way I can imagine.

查看更多
萌系小妹纸
3楼-- · 2019-01-11 15:45

The answer is: it's all about permissions.

It's not enough to place the file in the correct location, like, such instance: /usr/local/lib/python2.7/dist-packages, you also need to ensure that the file can be read by the process you're running, in this case, python.

Be sure that "other" users have read access to the file. Open the bash console and execute this:

sudo chmod o+r "yourmodule.py"
[Introduce the password]

After this go again to python and try the import:

import "yourmodule"

As long as the path where the .py file is located is present in PYTHONPATH + the file is readable then you should be allowed to import it.

查看更多
家丑人穷心不美
4楼-- · 2019-01-11 15:49

In one of the directories listed when you type sys.path in your Python prompt. You can also add the directory which contains your file by modifiying the PYTHONPATH environment variable:

# ~/.bashrc file
export PYTHONPATH+=:/some/dir
查看更多
Melony?
5楼-- · 2019-01-11 15:56

Couple of things.

First the module must, (I believe), be in a directory that matches the module name.

Put that module directory under one of the directories in the PYTHONPATH (I use /usr/lib/pymodules/pythonV.x/). You can find a suitable directory in the path using

import sys
print(sys.path)

from the python prompt.

查看更多
贪生不怕死
6楼-- · 2019-01-11 15:58

If you're using Ubuntu, copy files to /usr/local/lib/python2.7/dist-packages. Following command will show you where to copy.

python -c "from distutils.sysconfig import *; print(get_python_lib())"

If you are the only one use the module, copy files to ~/.local/lib/python2.7/site-packages.

查看更多
登录 后发表回答