python how to get the program that has imported a module - python

I ran into some trouble with modules lately. I'm having a hard timefiguring out how I can get the file that has imported the module. basically:
import sys
imported = sys.get_modules_that_have_imported_this_script()
#and then the rest of the code
to be more specific. modules run when you import them right? so is there a way to get what program the module is running from? (preferably the path or file name)
edit: i want the file name so I can use the inspect module to get source code
edit2: I don't want to get the source of the module. I want to find the main program from a module imported within it
edit3: maybe this will help
https://pasteboard.co/OMO6tQoTKALI.png

I found the answer in here How to get filename of the __main__ module in Python?
If you have two files main.py and module.py, this is how you can find the path of main.py from module.py
main.py
import module
module.function()
module.py
import __main__
main_filename = __main__.__file__
def function():
...

Related

import .py script on same folder

I've a python file named sample.py which has some functions and another python file from which I want to access the functions of the sample.py. I've tried the code below which is working fine if I include the directory in the import statement.
from Integrated.sample import *
But the folder can't be the same for my application. Also, I referred another problem in stackoverflow similar to my issue, tried one of the answers
from .sample import *
which gives the following error
ModuleNotFoundError: No module named '__main__.crypto'; '__main__' is not a package
directory structure:
-module
--__init__.py
--sample.py
--tester.py
Hoping for a solution
Thanks in advance
If they are in the same module, you can directly import the file as given below. Works for me.
sample.py
def myfun():
print("Sample")
tester.py
from sample import myfun
myfun()
Output
$ python3 tester.py
Sample
If I understand you question correctly, you would like to import a python module from another python folder.
I see you already have a __init__.py file that is needed to declare this folder is a python package.
Navigate to the file where you want to import the module.
from root.parent.folder.file import function_name
other way of doing it
import sys
import os
sys.path.append(os.path.abspath("/home/helloworld"))
from helloworld import *
Hope this helps.

Importing a fixed module from a dynamic path at runtime in python3

I have searched around and not found a solution to this particular Python3 problem. Perhaps it's the keywords I'm using, or it could be just a special use case. In the event that my problem is the latter, here is my question:
I'm developing a python (3) script which needs to use a python module which has been compiled locally in the user's home directory. I do not have anything so fancy as a configure script to configure this path for the user as an automated process. I want to pass the path to the python module to the script at runtime as a command line argument, and then dynamically load that module. For example, I will call:
$ myscript.py --modpath /home/user/path/to/ModuleSource
and then in my code call something like the following when I parse the command line arguments:
import sys
sys.path.append(localModulePath)
import GlobalModuleName
The problem is that in the static code for my script which uses the module methods, the actual module cannot be resolved until runtime when the definitions for the module are passed to my script.
That is, if I have python code like the following
GlobalModuleName.moduleFunc()
I get runtime errors of "NameError: name 'GlobalModuleName' is not defined".
How do I get this configuration to work without generating an error? I am certain that the code that will use the dynamic definitions of the module is correct. Thanks for the pointers in advance.
This worked perfectly for me
module1.py
import os
import sys
def func1():
print("Executed func1 of module1")
main.py
import sys
pathPassed=sys.argv[1]
sys.path.append(pathPassed)
import module1
module1.func1()
Execution
python main.py ThePathformodule1.py
Executed func1 of module1
The only thing you have to take care is that the import statement should be after the sys.path.append

Python module importing functions

I'm trying to get my head around Python modules. I currently have the current setup. My main code in file test.py:
from superpackage import supermodule
supermodule.woww()
I then have a directory named superpackage inside this folder is the module file supermodule.py defined as so:
def woww():
print "wow"
In the same directory I have a blank __init__.py.
The code executes. Is there a way to import the contents of the package so I can just call woww() without the supermodule.? When working with just modules I can do from supermodule import woww, but is there an equivalent for packages?

Python Import Module

Recently started a new Python project.
I am resolving a import module error where I am trying to import modules from the same directory.
I was following the solutions here but my situation is slightly different and as a result my script cannot run.
My project directory is as follows:
dir-parent
->dir-child-1
->dir-child-2
->dir-child-3
->__init__.py (to let python now that I can import modules from here)
->module1
->module2
->module3
->module4
->main.py
In my main.py script I am importing these module in the same directory as follows:
from dir-parent.module1 import class1
When I run the script using this method it throws a import error saying that there is no module named dir-parent.module1 (which is wrong because it exists).
I then change the import statement to:
from module1 import class1
and this seemed to resolve the error, however, the code I am working on has been in use for over 2.5 years and it has always imported modules via this method, plus in the code it refers to the dir-parent directory.
I was just wondering if there is something I am missing or need to do to resolve this without changing these import statements and legacy code?
EDIT: I am using PyCharm and am running off PyCharm
If you want to keep the code unchanged, I think you will have to add dir-parent to PYTHONPATH. For exemple, add the following on top of your main.py :
import os, sys
parent_dir = os.path.abspath(os.path.dirname(__file__)) # get parent_dir path
sys.path.append(parent_dir)
Python's import and pathing are a pain. This is what I do for modules that have a main. I don't know if pythonic at all.
# Add the parent directory to the path
CURRENTDIR = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
if CURRENTDIR not in sys.path:
sys.path.append(CURRENTDIR)

trying to import a *.pyc as a module

I have a python script that is trying to import another script somewhere in the file-system (path is only known at runtime).
To my understanding I need to use the imp module and this might work, but when loading the module I get an error that modules used by the imported module are not found.
Heres the code:
importer.py:
import imp
imp.load_compiled("my_module","full_path_to_my_module\\my_module.pyc")
my_module.py:
import sys
import another_module
When I run importer.py I get htis error message:
ImportError: No module named another_module
Whats going wrong here ?
I suspect that when 'importer.py' is loading 'my_module.pyc' hes also trying to load 'another_module' (thats good) but is looking in the wrong place (eg not 'full_path_to_my_module')
EDIT:
I tried adding 'full_path_to_my_module' to the system path:
import imp
import sys
sys.path.append(full_path_to_my_module)
imp.load_compiled("my_module",full_path_to_my_module+my_module)
But I still get the same error
Maybe I do something thats not necessary - Here's my goal:
I want to be able to use all functionality of 'my_module.pyc' inside 'importer.py'. But the location of 'my_module.pyc' is given as a parameter to 'importer.py'.
imp.load_compiled returns the compiled module object, it is different to the import statement which also binds the module to a name
import imp
my_module = imp.load_compiled("my_module", "full_path_to_my_module/my_module.pyc")
Then you can do something like:
my_module.yayfunctions('a')
Complete example session:
$ cat /tmp/my_module.py
def yayfunctions(a):
print a
$ python -m compileall /tmp/my_module.py
$ ls /tmp/my_module.py*
my_module.py my_module.pyc
$ python
>>> import imp
>>> my_module = imp.load_compiled("my_module", "/tmp/my_module.pyc")
>>> my_module.yayfunctions('a')
a
Edit regarding comment (ImportError: No module named another_module), I assume the error is caused by the code in my_module.pyc, and the another_module.py lives in the same directory
In that case, as others have suggested, it's simpler to just add the directory containing my_module to sys.path and use the regular import mechanism, specifically __import__
Here's a function which should do what you want:
import os
def load_path(filepath):
"""Given a path like /path/to/my_module.pyc (or .py) imports the
module and returns it
"""
path, fname = os.path.split(filepath)
modulename, _ = os.path.splitext(fname)
if path not in sys.path:
sys.path.insert(0, path)
return __import__(modulename)
if __name__ == '__main__':
# Example usage
my_module = load_path('/tmp/my_module.py')
my_module.yayfunctions('test')
It is since at the scope of import another_module your "full_path_to_my_module" isn't known.
Have you tried to add the path to known paths instead, i.e.:
import sys
sys.path.append("full_path_to_my_module")
You don't actually need to use the imp module to load pyc modules.
An easy way to try it out is to make two python modules, one importing from the other and run it. Delete then the imported .py file so you only get the .pyc file left: when running the script the import will work just fine.
But, for importing py files from random directories, you may want to add that directory to the python path first before importing it.
For instance:
import sys
sys.path.insert(0, "/home/user/myrandomdirectory")
Loading pyc files works the exact same way as loading a py file except it doesn't do a compile step. Thus just using import mymodule will work as long as the version number of the pyc is the same as the python you're running. Otherwise you'll get a magic number error.
If you module isn't in your path you'll need to add that to sys -- or if its a subdirectory, add a __init__.py file to that directory..

Categories