問題描述
我面臨類似于 Py_initialize/Py_Finalize 的問題不能用 numpy 工作兩次 .. C 中的基本編碼:
I am facing a problem similar to the Py_initialize / Py_Finalize not working twice with numpy .. The basic coding in C:
Py_Initialize();
import_array();
//Call a python function which imports numpy as a module
//Py_Finalize()
程序處于循環中,如果 python 代碼將 numpy 作為導入的模塊之一,它會給出段錯誤.如果我刪除 numpy,它工作正常.
The program is in a loop and it gives a seg fault if the python code has numpy as one of the imported module. If I remove numpy, it works fine.
作為臨時解決方法,我嘗試不使用 Py_Finalize(),但這會導致巨大的內存泄漏 [隨著 TOP 的內存使用量不斷增加而觀察到].我試過但不明白我發布的那個鏈接中的建議.有人可以建議在導入諸如 numpy 的同時完成通話的最佳方法.
As a temporary work around I tried not to use Py_Finalize(), but that is causing huge memory leaks [ observed as the memory usage from TOP keeps on increasing ]. And I tried but did not understand the suggestion in that link I posted. Can someone please suggest the best way to finalize the call while having imports such as numpy.
謝謝桑托什
推薦答案
我不太確定您似乎不理解 Py_initialize/Py_Finalize 不能與 numpy 一起工作兩次.發布的解決方案非常簡單:每次程序執行時只調用 Py_Initialize 和 Py_Finalize 一次.不要在每次運行循環時都調用它們.
I'm not quite sure how you don't seem to understand the solution posted in Py_initialize / Py_Finalize not working twice with numpy. The solution posted is quite simple: call Py_Initialize and Py_Finalize only once for each time your program executes. Do not call them every time you run the loop.
我假設您的程序在啟動時會運行一些初始化命令(僅運行一次).在那里調用 Py_Initialize.永遠不要再調用它.另外,我假設當你的程序終止時,它有一些代碼可以刪除東西、轉儲日志文件等.在那里調用 Py_Finalize.Py_Initialize 和 Py_Finalize 并非旨在幫助您管理 Python 解釋器中的內存.不要為此使用它們,因為它們會導致您的程序崩潰.相反,請使用 Python 自己的函數來刪除您不想保留的對象.
I assume that your program, when it starts, runs some initialization commands (which are only run once). Call Py_Initialize there. Never call it again. Also, I assume that when your program terminates, it has some code to tear down things, dump log files, etc. Call Py_Finalize there. Py_Initialize and Py_Finalize are not intended to help you manage memory in the Python interpreter. Do not use them for that, as they cause your program to crash. Instead, use Python's own functions to get rid of objects you don't want to keep.
如果您確實必須在每次運行代碼時創建一個新環境,您可以使用 Py_NewInterpreter 并創建一個子解釋器,然后使用 Py_EndInterpreter 來銷毀該子解釋器.它們記錄在 Python C API 頁面底部附近.這類似于擁有一個新的解釋器,除了每次啟動子解釋器時不會重新初始化模塊.
If you really MUST create a new environment every time you run your code, you can use Py_NewInterpreter and to create a sub-interpreter and Py_EndInterpreter to destroy that sub-interpreter later. They're documented near the bottom of the Python C API page. This works similarly to having a new interpreter, except that modules are not re-initialized each time a sub-interpreter starts.
這篇關于Python - C 嵌入式分段錯誤的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!