Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the absolute path of an imported module

Tags:

How can I get the absolute path of an imported module?

like image 922
Determinant Avatar asked Sep 02 '12 06:09

Determinant


People also ask

How do you find the absolute path of a Python module?

Use abspath() to Get the Absolute Path in Python To get the absolute path using this module, call path. abspath() with the given path to get the absolute path. The output of the abspath() function will return a string value of the absolute path relative to the current working directory.

How do I import absolute path?

import * as file4 from './file4'; An absolute import path is a path that starts from a root, and you need to define a root first. In a typical JavaScript/TypeScript project, a common root is the src directory. For file1.

How do you use absolute import in Python?

Absolute import involves full path i.e., from the project's root folder to the desired module. An absolute import state that the resource to be imported using its full path from the project's root folder.

What is __ path __ in Python?

If you change __path__ , you can force the interpreter to look in a different directory for modules belonging to that package. This would allow you to, e.g., load different versions of the same module based on runtime conditions.


1 Answers

As the other answers have said, you can use __file__. However, note that this won't give the full path if the other module is in the same directory as the program. So to be safe, do something like this:

>>> import os >>> import math >>> os.path.abspath(math.__file__) '/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/math.so' 

Here's an example with a module I made called checkIP to illustrate why you need to get the abspath (checkIP.py is in the current directory):

>>> import os >>> import checkIP >>> os.path.abspath(checkIP.__file__) '/Users/Matthew/Programs/checkIP.py' >>> checkIP.__file__ 'checkIP.py' 
like image 73
Matthew Adams Avatar answered Oct 03 '22 22:10

Matthew Adams