I'm trying to use Python.NET from F#. Before using Python.NET from F#, I used it from C#. In order to get my code to work from C#, I had to set the path to a local Python dll with: Runtime.PythonDLL = "C:/Users/name/miniconda3/python39.dll";
.
Now I'm trying Python.NET from F#, but it doesn't work. I used this example code :
open Python.Runtime // dotnet add package pythonnet --version 3.0.1
open FSharp.Interop.Dynamic // dotnet add package FSharp.Interop.Dynamic --version 5.0.1.268
open System.Collections.Generic
[<EntryPoint>]
let main argv =
//set up for garbage collection?
use gil = Py.GIL()
//-----
//NUMPY
//import numpy
let np = Py.Import("numpy")
//call a numpy function dynamically
let sinResult = np?sin(5)
// more code
0
When I run this code I get
System.TypeInitializationException
HResult=0x80131534
Message=The type initializer for 'Delegates' threw an exception.
Source=Python.Runtime
StackTrace:
at Python.Runtime.Runtime.Delegates.get_PyGILState_Ensure()
at Python.Runtime.Runtime.PyGILState_Ensure()
at Python.Runtime.Py.GIL()
at Program.main(String[] argv) in D:\Repos\TcBlack\src\Fblark\Program.fs:line 20
Inner Exception 1:
BadPythonDllException: Runtime.PythonDLL was not set or does not point to a supported Python runtime DLL. See https://github.com/pythonnet/pythonnet#embedding-python-in-net
Inner Exception 2:
MissingMethodException: Failed to load symbol Py_IncRef.
Inner Exception 3:
Win32Exception: The specified procedure could not be found
I figured this is because I didn't set the Python dll location. But since I can't do Runtime.PythonDLL = "C:/Users/name/miniconda3/python39.dll"
in F#, I'm not sure how to continue. Any ideas?
You can set the Python paths with Environment.SetEnvironmentVariable
as also shown in this C# example .
open Python.Runtime
open FSharp.Interop.Dynamic
open System
open System.IO
[<EntryPoint>]
let main argv =
let pythonBasePath = "C:/Users/user/miniconda3"
Environment.SetEnvironmentVariable("PYTHONHOME", pythonBasePath)
Environment.SetEnvironmentVariable("PYTHONNET_PYDLL", Path.Combine(pythonBasePath, "python39.dll"));
PythonEngine.Initialize();
PythonEngine.BeginAllowThreads();
use gil = Py.GIL()
let np = Py.Import("numpy")
//call a numpy function dynamically
let sinResult = np?sin(5)
printfn "%A" sinResult
0
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.