簡體   English   中英

如何在F#中為Python.NET設置Python路徑?

[英]How do I set the Python path for Python.NET in F#?

我正在嘗試使用來自 F# 的 Python.NET。在使用來自 F# 的 Python.NET 之前,我使用了來自 C# 的它。為了讓我的代碼從 C# 開始工作,我必須將路徑設置為本地 Python 88103788845 with: Runtime.PythonDLL = "C:/Users/name/miniconda3/python39.dll"; .

現在我正在嘗試來自 F# 的 Python.NET,但它不起作用。 我使用了這個示例代碼

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

當我運行這段代碼時,我得到

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

我認為這是因為我沒有設置 Python dll 位置。 但是由於我不能在 F# 中執行Runtime.PythonDLL = "C:/Users/name/miniconda3/python39.dll" ,所以我不確定如何繼續。 有任何想法嗎?

您可以使用Environment.SetEnvironmentVariable設置 Python 路徑,如C# 示例中所示。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM