Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python - Importing a file that is a symbolic link

If I have files x.py and y.py . And y.py is the link(symbolic or hard) of x.py .

If I import both the modules in my script. Will it import it once or it assumes both are different files and import it twice.

What it does exactly?

like image 345
leela Avatar asked Jul 21 '09 09:07

leela


People also ask

Is a symbolic link a file?

A symlink (also called a symbolic link) is a type of file in Linux that points to another file or a folder on your computer. Symlinks are similar to shortcuts in Windows. Some people call symlinks "soft links" – a type of link in Linux/UNIX systems – as opposed to "hard links."

How do I import a file into a python script?

If you have your own python files you want to import, you can use the import statement as follows: >>> import my_file # assuming you have the file, my_file.py in the current directory. # For files in other directories, provide path to that file, absolute or relative.

What is a symbolic link in Python?

In computing, a symbolic link (also symlink or soft link) is a file whose purpose is to point to a file or directory (called the "target") by specifying a path thereto. Symbolic links are supported by POSIX and by most Unix-like operating systems, such as FreeBSD, Linux, and macOS.


2 Answers

Python will import it twice.

A link is a file system concept. To the Python interpreter, x.py and y.py are two different modules.

$ echo print \"importing \" + __file__ > x.py
$ ln -s x.py y.py
$ python -c "import x; import y"
importing x.py
importing y.py
$ python -c "import x; import y"
importing x.pyc
importing y.pyc
$ ls -F *.py *.pyc
x.py  x.pyc  y.py@  y.pyc
like image 148
codeape Avatar answered Sep 21 '22 06:09

codeape


You only have to be careful in the case where your script itself is a symbolic link, in which case the first entry of sys.path will be the directory containing the target of the link.

like image 33
Neil Avatar answered Sep 24 '22 06:09

Neil