Import to Python

Can I import modules based on location?

(for example, all the modules I import should be in / usr / lib64 / python2.5 / or a similar directory?)

I would like to import a module, local, into the current script.

+3
source share
7 answers

You can extend the runtime path as follows:

sys.path.extend(map(os.path.abspath, ['other1/', 'other2/', 'yourlib/']))
+9
source

You can edit PYTHONPATH to add or remove locations that python will look for when you try to import.

+3
source
  • python .

  • sys.path - , , python .

+3

, , , . :

: mod1.py, mod2.py

mod2.py
--------
import mod1

PYTHON_PATH:

import sys
sys.path.extend('/user/some/other/directory')
import mod1
0

./lib.

0

imp .

, foo.py:

def x():
    print 'hello, world'

:

import imp

with open('foo.py', 'r') as module_file:
    imp.load_module('module_name', module_file, '', ('', 'r', imp.PY_SOURCE))

import module_name

module_name.x()

", ".

0

init.py

sys.path , script . , .

, :

~/foo/__init__.py
~/foo/foo.py
~/foo/bar/__init__.py
~/foo/bar/baz.py

init.py - , , foo.py baz.py - python. - :

import sys
try:
    from foo import foo
    from foo.bar import baz
except ImportError:
    "%s is not in %s. Add to your PYTHONPATH in ~/.bashrc" % \
    (os.path.expanduser("~/foo"),sys.path)

- , , . , , , / . . '~/foo' ~ ~/downloads/foo, :

cd ~
ln -s ~/downloads/foo foo

- .

0

Source: https://habr.com/ru/post/1706619/


All Articles