I have a script that runs without any problems using Pycharm / Spyder but when I try to run in using Iron Python on c# I get the following error: 'No module named keras.callbacks'
Here is the code I am using to run the script:
public string PatchParameter(string parameter, int serviceid)
{
var engine = Python.CreateEngine(); // Extract Python language engine from their grasp
var scope = engine.CreateScope(); // Introduce Python namespace (scope)
var d = new Dictionary<string, object>
{
{ "serviceid", serviceid},
{ "parameter", parameter}
}; // Add some sample parameters. Notice that there is no need in specifically setting the object type, interpreter will do that part for us in the script properly with high probability
scope.SetVariable("params", d); // This will be the name of the dictionary in python script, initialized with previously created .NET Dictionary
ICollection<string> searchPaths = engine.GetSearchPaths();
searchPaths.Add(#"D:\Projects\xxx");
searchPaths.Add(#"C:\Users\xxx\Anaconda3");
searchPaths.Add(#"C:\Users\xxx\Anaconda3\Library\bin");
searchPaths.Add(#"C:\Users\xxx\Anaconda3\Scripts");
searchPaths.Add(#"D:\Projects\SmartTrader\venv");
searchPaths.Add(#"D:\Projects\SmartTrader\venv\Scripts");
searchPaths.Add("..\\..");
engine.SetSearchPaths(searchPaths);
ScriptSource source = engine.CreateScriptSourceFromFile(#"D:\Projects\xxx\Main.py"); // Load the script
object result = source.Execute(scope);
parameter = scope.GetVariable<string>("parameter"); // To get the finally set variable 'parameter' from the python script
return parameter;
}
In the comments it was suggested to add the virtual environment to the search paths, that still did not work though.
I also tried running it through regular CMD and it did not work as well:
C:\Users\xxx\Anaconda3>python.exe D:\Projects\xxx\Main.py
Traceback (most recent call last):
File "D:\Projects\xxx\Main.py", line 7, in <module>
import Config as cfg
File "D:\Projects\xxx\Config.py", line 2, in <module>
from keras.callbacks import EarlyStopping, ModelCheckpoint
ModuleNotFoundError: No module named 'keras'
I tried adding the Anaconda paths to its search paths but it did not work.
What am I missing?
Thanks
Amit
You can't run an Anaconda environment with IronPython, sorry.
(You especially probably can't run Keras / Tensorflow on IronPython.)
Related
I have a C# piece that generates a DLL which I'm trying to invoke from Python. The C# prototype is as follow:
public Main(NationalInstruments.TestStand.Interop.API.SequenceContext sequenceContext){
public void ShowFullOptions(out bool errorOccurred, out int errorCode, out String errorMsg) {
[...]
}
}
I followed this post which explains how to achieve to pass "out" parameters from python, without success since clr.Reference does not exist and throw me the error:
AttributeError: module 'clr' has no attribute 'Reference'
I have pythonnet installed, version 2.3.
My python code:
import clr
dll_path = R"thatDllPath.dll"
clr.AddReference(dll_path)
from Flamenco_Calibration_Interface import Main
import System
my_instance = Main(None)
v1 = clr.Reference[System.Boolean](False)
v2 = clr.Reference[System.Int64](1)
v3 = clr.Reference[System.String]("")
a = my_instance.ShowFullOptions(v1,v2,v3)
I have checked that the DLL path is good and I am able to successfully call the C# method if I overload "ShowFullOptions" with a version without any arguments.
The main problem resides in that I have the "out" keyword in the C# method prototype.
How do you properly generate argument in python so they are accepted as "out" within C# ?
Any help much appreciated.
I've created a python binding for one of my projects a while back and just now wanted to pick it up again.
The binding was no longer working as python was no longer able to import it - this all was working fine back then.
I've then decided to break it down to the simplest possible example:
binding.cpp
#include <pybind11/pybind11.h>
int add(int i, int j) {
return i + j;
}
PYBIND11_MODULE(TestBinding, m) {
m.doc() = "pybind11 example plugin"; // optional module docstring
m.def("add", &add, "A function which adds two numbers");
}
CMakeLists.txt:
cmake_minimum_required( VERSION 3.2 )
project(TestBinding)
add_subdirectory(pybind11) # or find_package(pybind11)
pybind11_add_module(TestBinding binding.cpp)
# Configure project to inject source path as include directory on dependent projects
target_include_directories( TestBinding
INTERFACE
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}>
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/pybind11/include/> )
set_target_properties( TestBinding
PROPERTIES
CXX_STANDARD 17
CXX_STANDARD_REQUIRED ON
PREFIX ""
SUFFIX ".so"
)
Then I have a very simple test.py file which goes like this:
sys.path.insert(0, "/path/to/so/lib/")
from TestBinding import *
...which once executed always gives me the following error:
from TestBinding import *
ModuleNotFoundError: No module named 'TestBinding'
I have literally no idea anymore what in the world could have changed from when it worked just fine and now.
Here are some more informations about my working environment:
Windows 10
Visual Studio 15 2017 Win64
Python 3.7 (also tried 3.5 and 3.6)
Am I missing anything really obvious?
I've been able to resolve this by removing the SUFFIX ".so" rule from my CMakeLists.txt.
This was needed back when I've initially created my bindings, but it no longer is apparently.
I have the same problem as you. After checking, it is found that the problem is caused by the inconsistency between the python version of pybind11 and the python version of the local environment. My problem was solved when I adjusted to the same python version.
I'm trying to use some Python Code in my Swift project with PythonKit. In order to do that, I've downloaded the new Xcode 11 to add PythonKit as Swift Package.
After adding PythonKit with Swift Package, I have these project dependencies right here.
I want to use my Python code at the start of my app, so I put the call for Python code in my App Delegate, in the application function.
import UIKit
import PythonKit
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
let sys = Python.import("sys")
print("Python Version: \(sys.version)")
sys.path.append("/Users/me/Documents/MyProject/MyPackage/my_python_main_file")
let pythonAPI = Python.import("my_python_main_file")
pythonAPI.main_function.call()
return true
}
After running my project, I get the following error :
Fatal error: Python library not found. Set the PYTHON_LIBRARY environment variable with the path to a Python library.
I tried to follow the different steps with Breakpoints to know where the code actually crashes. So here is the different stages the PythonKit goes through :
It goes inside PythonLibrary init() and produces the error :
guard let pythonLibraryHandle = PythonLibrary.loadPythonLibrary() else {
fatalError("""
Python library not found. Set the \(Environment.library.key) \
environment variable with the path to a Python library.
""")
}
After investigation, it is because of the call of dlopen inside of loadPythonLibrary function
static func loadPythonLibrary(at path: String) -> UnsafeMutableRawPointer? {
log("Trying to load library at '\(path)'...")
#if canImport(Darwin) || canImport(Glibc)
// Must be RTLD_GLOBAL because subsequent .so files from the imported python
// modules may depend on this .so file.
let pythonLibraryHandle = dlopen(path, RTLD_LAZY | RTLD_GLOBAL)
#elseif os(Windows)
let pythonLibraryHandle = UnsafeMutableRawPointer(LoadLibraryA(path))
#endif
if pythonLibraryHandle != nil {
log("Library at '\(path)' was sucessfully loaded.")
}
return pythonLibraryHandle
}
This functions returns nil, which is due to dlopen function returning nil.
However, I checked the path given as parameter to loadPythonLibrary(at : path) and it appeared to be correct (in Terminal I tried to do cd to the following path and it worked) :
/usr/local/Frameworks/Python.framework/Versions/2.7/Python
I am using Python 2.7 in my code.
Do you know why dlopen would return nil in my case ?
You can do it now using my fork of PythonKit at https://github.com/kewlbear/PythonKit. This package depends on my other package https://github.com/kewlbear/Python-iOS. Ultimately Python will be embedded in the app. Currently Python 3.8 is used.
From my C code, I am calling the fasttext language classifier. The fasttext language classifier is a python file. Now the python file is importing fasttext.
Now I am required to call this python file many a times from my C code on different different texts. The first call to this python file is working fine and is giving me the output.
But from the immediate next call to this I am getting the above error while importing fasttext.
My C code which calls the language detector is the following.
The first line of the python file languagedetector.py has import fasttext
which internally is calling import fasttext_pybind as fasttext (as I get it from trace)
And while doing so I get
ImportError: generic_type: type "args" is already registered!
How to get rid off this error.
Can anyone please help?
Py_SetProgramName("python3");
Py_Initialize();
wchar_t *argv[3];
argv[0] = Py_DecodeLocale("/home/languagedetector.py", NULL);
argv[1] = Py_DecodeLocale("-t", NULL);
argv[2] = Py_DecodeLocale("Hi DEbapriyay", NULL);
PySys_SetArgv(3,&argv);
FILE *file = fopen("/home/languagedetector.py", "r");
PyRun_SimpleFile(file, "/home/languagedetector.py");
PyMem_RawFree(argv[0]);
PyMem_RawFree(argv[1]);
PyMem_RawFree(argv[2]);
Py_Finalize();
i used jscript.net to create a .dll file.
as a test, i can successfully call the function hello() in another jscript.net program, which compiled as .exe.
BUT my question is:
how can i call the function in python?
this dll can be successfully loaded by using ctypes.windll.LoadLibrary("power.dll"). however, the name of function can't be found...
i have done some tests of my dll file.
i used "dumpbin /all" to check my dll, but i can't find any usable funciton names. it is odd...
the code of my dll file in jscript.net
""""""""""""""""""""""
import System;
import System.Console;
import System.IO;
package power{
public class testp {
function hello (){
var time_1 = DateTime.Now;
for (var i =0; i<10000; i++){
Console.WriteLine ("hello world!");
};
var time_2 = DateTime.Now;
Console.WriteLine (time_2-time_1);
};
};
};
""""""""""""""""""""""
Yes, you can consume any DLL in python if you make the code COM-exposed. I only skimmed through it, but this tutorial seems to give a good example of how to do this:
http://www.codeproject.com/Articles/73880/Using-COM-Objects-in-Scripting-Languages-Part-2-Py