Python: import a symbolic link into a folder

I have a folder A containing some Python and __init __ files. py.

If I copy the entire folder A to another folder B and create a file with "import A" there, it will work. But now I delete the folder and move to a symbolic link to the source folder. Now this does not work saying "Without a module named foo". Does anyone know how to use a symbolic link to import?

+6
source share
2 answers

Python does not check if your file is a symbolic link or not! Probably your problem is renaming modules or missing them in your search path!

If ModuleA becomes ModuleB and you try to import ModuleA, it cannot find it because it does not exist.

If you moved ModuleA to another directory and created a symbolic link with a different name that represents the new directory, this new directory should be the common parent directory of your script and your module, or the symlink directory should be in the search path.

By the way, this is not clear if you mean a module or package. The directory containing the __init__.py file becomes the package of all files with the extension .py (= modules) residing in it.

Example

 DIRA + __init__.py <-- makes DIRA to package DIRA + moduleA.py <-- module DIRA.moduleA 

Move and symbolic link

 /otherplace/DIRA <-+ | points to DIRA mylibraries/SYMA --+ symbolic link 

If SYMA has the same name as DIRA, and your script is in the SYMA directory, then it should work fine. If not, then you need to:

 import sys sys.path.append('/path/to/your/package/root') 

If you want to import a module from your SYMA package, you must:

 import SYMA.ModuleA 

Simple:

 import SYMA 

imports the package name, but not the modules in the package, into your namespace!

+7
source

This behavior can happen if your symbolic links are not configured correctly. For example, if you created them using relative file paths. In this case, symbolic links would be created without errors, but would not indicate meaning.

If this may be the cause of the error, use the full path to create the links and make sure they are correct using the ls links and observing the expected contents of the directory.

+2
source

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


All Articles