Overview
Hi I'm trying to integrate some python code that uses various libraries in a C# application, but even referencing the Lib folder isn't helping me.
C# code
var loader = "C:\\PythonNet\\PythonNetProvider\\loader.py";
var lib = "C:\\Python34\\Lib";
ICollection\<string\> paths = engine.GetSearchPaths();
paths.Add(loader);
paths.Add(lib);
engine.SetSearchPaths(paths);
var source = engine.CreateScriptSourceFromFile("C:\\PythonNet\\PythonNetProvider\\main.py");
var scope = engine.CreateScope();
var compiledSource = source.Compile();
//The line underneath is where the exception is being thrown
compiledSource.Execute(scope);
The exception is the following: IronPython.Runtime.Exceptions.ImportException: 'No module named 'errno''
loader.py
import pandas as pd
# other code
main.py
import loader
import copy
# other code
Conclusions
If I try to change the order of the two imports in the main.py the exception gives me the following message: IronPython.Runtime.Exceptions.ImportException: 'No module named '_weakref''
How can I solve these issues? Even using a different technology than IronPython
I've done pip install pandas and added the pandas folder path to the ICollection<string> paths but nothing changes
Related
I'm using Python 3.9.5.
Based on this post, I'm trying to reuse some functions from the parent directory. Here's my code hierarchy:
github_repository
src
base
string_utilities.py
validation
email_validator.py
I also have __init__.py in all folders. In ALL of them.
Here's the string_utilities.py content:
def isNullOrEmpty(text: str):
return text is not None and len(text) > 0
And here's the email_validator.py content:
from src.base import string_utilities
def is_email(text: str):
if string_utilities.isNullOrEmpty(text):
return False
# logic to check email
return True
Now when I run python email_validator.py, I get this error:
ModuleNotFoundError: No module named 'src'
I have changed that frustrating import statement to all of these different forms, and I still get no results:
from ...src.base import string_utilities
which results in:
ImportError: attempted relative import with no known parent package
import src.base.string_utilities
Which causes compiler to not know the isNullOrEmpty function.
import ...src.base.string_utilities
Which results in:
Relative imports cannot be used with "import .a" form; use "from . import a" instead
I'm stuck at this point on how to reuse that function in this file. Can someone please help?
I'm new to python and I'm having this problem that I can't figure it out.
My file structure is:
enter image description here
On Criador.py I have several functions, for example:
def doSomething():
pass
def doSomethingElse():
pass
and Im trying to use one of this functions on the Controller.py file:
The first thing I did was, on the Controller.py:
import Controller.Criador
and then tried to use that function as:
Controller.Criador.doSomething()
After running Controller.py, I got this error:
ModuleNotFoundError: No module named 'Controller.Criador'; 'Controller' is not a package
I tried several other things, like:
from . import Criador
or
from Controller.Criador import doSomething
or
from Controller import Criador
and nothing helped, just changed the errors to:
ImportError: cannot import name 'Criador'
and
ModuleNotFoundError: No module named 'Controller.Criador'; 'Controller' is not a package
and
ImportError: cannot import name 'Criador'
Can someone give me a light about this? I'm using PyCharm and it does not give me any error when I declare the imports, only when I run the file
If Controller.py and Criador.py are in the same folder, you can do this inside Controller.py:
import Criador
Criador.doSomething()
I'm trying to use a variable as a module to import from in Python.
Using ImportLib I have been successfully able to find the test...
sys.path.insert(0, sys.path[0] + '\\tests')
tool_name = selected_tool.split(".")[0]
selected_module = importlib.import_module("script1")
print(selected_module)
... and by printing the select_module I can see that it succesfully finds the script:
<module 'script1' from 'C:\\Users\\.....">
However, when I try to use this variable in the code to import a module from it:
from selected_module import run
run(1337)
The program quits with the following error:
ImportError: No module named 'selected_module'
I have tried to add a init.py file to the main directory and the /test directory where the scripts are, but to no avail. I'm sure it's just something stupidly small I'm missing - does anyone know?
Import statements are not sensitive to variables! Their content are treated as literals
An example:
urllib = "foo"
from urllib import parse # loads "urllib.parse", not "foo.parse"
print(parse)
Note that from my_module import my_func will simply bind my_module.my_func to the local name my_func. If you have already imported the module via importlib.import_module, you can just do this yourself:
# ... your code here
run = selected_module.run # bind module function to local name
I am trying to dynamically import modules in python.
I need something like a plugin import system.
I use the following code for import of a module, and it works fine, as long as the entire code of the module is in the same file.
caller.py code:
PluginFolder = "./plugins"
MainModule = "__init__"
possibleplugins = os.listdir(PluginFolder)
for possible_plugin in possibleplugins:
location = os.path.abspath(os.path.join(PluginFolder, possible_plugin))
if not os.path.isdir(location) or not MainModule + ".py" in os.listdir(location):
continue
info = imp.find_module(MainModule, [location])
plugin = {"name": possible_plugin, "info": info}
After that, I use the load_module method to load the module:
module = imp.load_module(MainModule, *plugin["info"])
The structure of the directories is as follows:
Project/
--plugins/
----plugin_1/
-------__init__.py
-------X.py
caller.py
Everything works great when all the methods are in the same file (__init__.py).
When the method I use in __init__.py calls another method from another file (in the same package) than an error saying "No module named X"
the __init__.py code fails at the line:
import X
I also tried
import plugin_1.X
and other variations.
Just to make sure you guys understand- importing and using the module in a normal way (not dynamically) works fine.
What am I missing?
Is there another way to do this? Maybe use the __import__ method, or something else?
I usually use importlib. It's load_module method does the job. You can put the importing code into plugins/__init__.py to do the following:
import importlib
import os
import logging
skip = set(("__init__.py",))
plugins = []
cwd = os.getcwd()
os.chdir(os.path.dirname(__file__))
for mod in glob.glob("*.py"):
if mod in skip:
continue
try:
mod = mod.replace(".py", "")
plugin = importlib.import_module("." + mod, __name__)
plugin.append(plugin)
except Exception as e:
logging.warn("Failed to load %s: %s. Skipping", mod, e)
os.chdir(cwd)
File setup:
...\Project_Folder
...\Project_Folder\Project.py
...\Project_folder\Script\TestScript.py
I'm attempting to have Project.py import modules from the folder Script based on user input.
Python Version: 3.4.2
Ideally, the script would look something like
q = str(input("Input: "))
from Script import q
However, python does not recognize q as a variable when using import.
I've tried using importlib, however I cannot figure out how to import from the Script folder mentioned above.
import importlib
q = str(input("Input: "))
module = importlib.import_module(q, package=None)
I'm not certain where I would implement the file path.
Repeat of my answer originally posted at How to import a module given the full path?
as this is a Python 3.4 specific question:
This area of Python 3.4 seems to be extremely tortuous to understand, mainly because the documentation doesn't give good examples! This was my attempt using non-deprecated modules. It will import a module given the path to the .py file. I'm using it to load "plugins" at runtime.
def import_module_from_file(full_path_to_module):
"""
Import a module given the full path/filename of the .py file
Python 3.4
"""
module = None
try:
# Get module name and path from full path
module_dir, module_file = os.path.split(full_path_to_module)
module_name, module_ext = os.path.splitext(module_file)
# Get module "spec" from filename
spec = importlib.util.spec_from_file_location(module_name,full_path_to_module)
module = spec.loader.load_module()
except Exception as ec:
# Simple error printing
# Insert "sophisticated" stuff here
print(ec)
finally:
return module
# load module dynamically
path = "<enter your path here>"
module = import_module_from_file(path)
# Now use the module
# e.g. module.myFunction()
I did this by defining the entire import line as a string, formatting the string with q and then using the exec command:
imp = 'from Script import %s' %q
exec imp