How to avoid Segmentation fault when calling Python scripts in Qt projectCalling an external command in PythonHow do I copy a file in Python?How can I safely create a nested directory?How do I parse a string to a float or int?How to get the current time in PythonHow can I make a time delay in Python?How can you profile a Python script?How do I get the number of elements in a list?How do I concatenate two lists in Python?How do I lowercase a string in Python?
Do all humans have an identical nucleotide sequence for certain proteins, e.g haemoglobin?
Uncovering the Accelerated Dragon opening
How do email clients "send later" without storing a password?
Relocation error, error code (127) after last updates
A medieval fantasy adventurer lights a torch in a 100% pure oxygen room. What happens?
The Planck constant for mathematicians
Fight a biblical flood apart from building barriers
Parallel resistance in electric circuits
Understanding Cursive /Joined Writing in Irish Register Death
Were Roman public roads build by private companies?
Where does the expression "triple-A" come from?
Can a corpse possessed by a Dybbuk be turned via Turn Undead?
Can the card disintegrate destroy creatures with indestructible?
Where to disclose a zero day vulnerability
Eccentric keepers
Is there a reliable way to hide/convey a message in vocal expressions (speech, song,...)
I was promised a work PC but still awaiting approval 3 months later so using my own laptop - Is it fair to ask employer for laptop insurance?
Why is Kirchoff's loop rule true in a DC circuit?
Glue or not to glue boots
Is a suit against a Univeristy Dorm for changing policies on a whim likely to succeed (USA)?
A shy person in a queue
Does my opponent need to prove his creature has morph?
Sol Ⅲ = Earth: What is the origin of this planetary naming scheme?
What does a Light weapon mean mechanically?
How to avoid Segmentation fault when calling Python scripts in Qt project
Calling an external command in PythonHow do I copy a file in Python?How can I safely create a nested directory?How do I parse a string to a float or int?How to get the current time in PythonHow can I make a time delay in Python?How can you profile a Python script?How do I get the number of elements in a list?How do I concatenate two lists in Python?How do I lowercase a string in Python?
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
I'm trying to call a function in Python under C++.
This is my attempt:
void myFuncion()
PyObject* fExportar = nullptr;
PyObject* modulo = nullptr;
PyObject* pName = nullptr;
const char *scriptDirectoryName = "path/of/my/pyfile";
Py_Initialize();
PyObject *sysPath = PySys_GetObject("path");
PyObject *path = PyUnicode_FromString(scriptDirectoryName);
int result = PyList_Insert(sysPath, 0, path);
if (result == 0 )//0 if ok, -1 if error
pName = PyUnicode_FromString("exportarXLS");//exportarXLS.py
modulo = PyImport_Import(pName);
Py_DECREF(path);
if (modulo)
fExportar = PyObject_GetAttrString(modulo, "exportar");//it crahs here
Py_DECREF(modulo);
if (fExportar)
//call the function
else
PyErr_Print();
Py_Finalize();
}
The problem is that my C++ program crashes if the python script has any wrong import
. In this case, I suspect that I trying to use an invalid version of PyQt4.
This is the module: (exportarXLS.py)
#!/usr/bin/python3
from PyQt4 import QtCore, QtGui, QtSql
def exportar():
print ("hello, I am probing")
Now my question:
Now I am beggining to probe the steps for develop a function for load python plugings, and I wonder how would I avoid the crash if someone want to add a script with wrong import
I have try to enclose the troubled line in a try/catch
block too, but it doesn't work.
EDIT:
I forgot to say that it's only happens into my Qt Project
If I try to run my function out of this I can get errors loading modules but it doesn't crash.
I've edited the tittle
python c++ pyqt
add a comment
|
I'm trying to call a function in Python under C++.
This is my attempt:
void myFuncion()
PyObject* fExportar = nullptr;
PyObject* modulo = nullptr;
PyObject* pName = nullptr;
const char *scriptDirectoryName = "path/of/my/pyfile";
Py_Initialize();
PyObject *sysPath = PySys_GetObject("path");
PyObject *path = PyUnicode_FromString(scriptDirectoryName);
int result = PyList_Insert(sysPath, 0, path);
if (result == 0 )//0 if ok, -1 if error
pName = PyUnicode_FromString("exportarXLS");//exportarXLS.py
modulo = PyImport_Import(pName);
Py_DECREF(path);
if (modulo)
fExportar = PyObject_GetAttrString(modulo, "exportar");//it crahs here
Py_DECREF(modulo);
if (fExportar)
//call the function
else
PyErr_Print();
Py_Finalize();
}
The problem is that my C++ program crashes if the python script has any wrong import
. In this case, I suspect that I trying to use an invalid version of PyQt4.
This is the module: (exportarXLS.py)
#!/usr/bin/python3
from PyQt4 import QtCore, QtGui, QtSql
def exportar():
print ("hello, I am probing")
Now my question:
Now I am beggining to probe the steps for develop a function for load python plugings, and I wonder how would I avoid the crash if someone want to add a script with wrong import
I have try to enclose the troubled line in a try/catch
block too, but it doesn't work.
EDIT:
I forgot to say that it's only happens into my Qt Project
If I try to run my function out of this I can get errors loading modules but it doesn't crash.
I've edited the tittle
python c++ pyqt
Not able to reproduce a crash for this. If the module fails to load, I don't get a crash, I just get a NULL. The duct tape workaround doesn't really help here as it's most likely an environment issue that's triggering the problem which you need to get to the root of. You can try with the environment variablePYTHONVERBOSE
to see the difference between loading via C++ and loading from python3 directly to see if there's a difference there. I'll give you an option for an 'in the event of a SEGV', but you need to determine the why of it.
– Petesh
Mar 28 at 12:09
add a comment
|
I'm trying to call a function in Python under C++.
This is my attempt:
void myFuncion()
PyObject* fExportar = nullptr;
PyObject* modulo = nullptr;
PyObject* pName = nullptr;
const char *scriptDirectoryName = "path/of/my/pyfile";
Py_Initialize();
PyObject *sysPath = PySys_GetObject("path");
PyObject *path = PyUnicode_FromString(scriptDirectoryName);
int result = PyList_Insert(sysPath, 0, path);
if (result == 0 )//0 if ok, -1 if error
pName = PyUnicode_FromString("exportarXLS");//exportarXLS.py
modulo = PyImport_Import(pName);
Py_DECREF(path);
if (modulo)
fExportar = PyObject_GetAttrString(modulo, "exportar");//it crahs here
Py_DECREF(modulo);
if (fExportar)
//call the function
else
PyErr_Print();
Py_Finalize();
}
The problem is that my C++ program crashes if the python script has any wrong import
. In this case, I suspect that I trying to use an invalid version of PyQt4.
This is the module: (exportarXLS.py)
#!/usr/bin/python3
from PyQt4 import QtCore, QtGui, QtSql
def exportar():
print ("hello, I am probing")
Now my question:
Now I am beggining to probe the steps for develop a function for load python plugings, and I wonder how would I avoid the crash if someone want to add a script with wrong import
I have try to enclose the troubled line in a try/catch
block too, but it doesn't work.
EDIT:
I forgot to say that it's only happens into my Qt Project
If I try to run my function out of this I can get errors loading modules but it doesn't crash.
I've edited the tittle
python c++ pyqt
I'm trying to call a function in Python under C++.
This is my attempt:
void myFuncion()
PyObject* fExportar = nullptr;
PyObject* modulo = nullptr;
PyObject* pName = nullptr;
const char *scriptDirectoryName = "path/of/my/pyfile";
Py_Initialize();
PyObject *sysPath = PySys_GetObject("path");
PyObject *path = PyUnicode_FromString(scriptDirectoryName);
int result = PyList_Insert(sysPath, 0, path);
if (result == 0 )//0 if ok, -1 if error
pName = PyUnicode_FromString("exportarXLS");//exportarXLS.py
modulo = PyImport_Import(pName);
Py_DECREF(path);
if (modulo)
fExportar = PyObject_GetAttrString(modulo, "exportar");//it crahs here
Py_DECREF(modulo);
if (fExportar)
//call the function
else
PyErr_Print();
Py_Finalize();
}
The problem is that my C++ program crashes if the python script has any wrong import
. In this case, I suspect that I trying to use an invalid version of PyQt4.
This is the module: (exportarXLS.py)
#!/usr/bin/python3
from PyQt4 import QtCore, QtGui, QtSql
def exportar():
print ("hello, I am probing")
Now my question:
Now I am beggining to probe the steps for develop a function for load python plugings, and I wonder how would I avoid the crash if someone want to add a script with wrong import
I have try to enclose the troubled line in a try/catch
block too, but it doesn't work.
EDIT:
I forgot to say that it's only happens into my Qt Project
If I try to run my function out of this I can get errors loading modules but it doesn't crash.
I've edited the tittle
python c++ pyqt
python c++ pyqt
edited Mar 29 at 11:02
user3733164
asked Mar 28 at 9:53
user3733164user3733164
2201 silver badge10 bronze badges
2201 silver badge10 bronze badges
Not able to reproduce a crash for this. If the module fails to load, I don't get a crash, I just get a NULL. The duct tape workaround doesn't really help here as it's most likely an environment issue that's triggering the problem which you need to get to the root of. You can try with the environment variablePYTHONVERBOSE
to see the difference between loading via C++ and loading from python3 directly to see if there's a difference there. I'll give you an option for an 'in the event of a SEGV', but you need to determine the why of it.
– Petesh
Mar 28 at 12:09
add a comment
|
Not able to reproduce a crash for this. If the module fails to load, I don't get a crash, I just get a NULL. The duct tape workaround doesn't really help here as it's most likely an environment issue that's triggering the problem which you need to get to the root of. You can try with the environment variablePYTHONVERBOSE
to see the difference between loading via C++ and loading from python3 directly to see if there's a difference there. I'll give you an option for an 'in the event of a SEGV', but you need to determine the why of it.
– Petesh
Mar 28 at 12:09
Not able to reproduce a crash for this. If the module fails to load, I don't get a crash, I just get a NULL. The duct tape workaround doesn't really help here as it's most likely an environment issue that's triggering the problem which you need to get to the root of. You can try with the environment variable
PYTHONVERBOSE
to see the difference between loading via C++ and loading from python3 directly to see if there's a difference there. I'll give you an option for an 'in the event of a SEGV', but you need to determine the why of it.– Petesh
Mar 28 at 12:09
Not able to reproduce a crash for this. If the module fails to load, I don't get a crash, I just get a NULL. The duct tape workaround doesn't really help here as it's most likely an environment issue that's triggering the problem which you need to get to the root of. You can try with the environment variable
PYTHONVERBOSE
to see the difference between loading via C++ and loading from python3 directly to see if there's a difference there. I'll give you an option for an 'in the event of a SEGV', but you need to determine the why of it.– Petesh
Mar 28 at 12:09
add a comment
|
3 Answers
3
active
oldest
votes
Duck tape solution :
void signal_handler(int signal)
std::cout << "Usefull information" std::endl;
exit(1);
...
std::signal(SIGSEGV, signal_handler);
Doc : https://en.cppreference.com/w/cpp/utility/program/signal
I think this kind of solution should be used only in debug
add a comment
|
It would be best to deal with the problem by finding out the underlying cause of the SEGV as the state of your application could be seriously damaged by it being triggered.
If you want to attempt to catch the SEGV in a semi-structured manner then you can use something like the sample code, which uses sigsetjmp
and siglongjmp
:
#include <python3.7m/Python.h> // That's my python
#include <setjmp.h>
#include <signal.h>
static sigjmp_buf env;
static void
catch_segv(int func)
siglongjmp(env, 1);
int myFunction()
PyObject* fExportar = nullptr;
PyObject* modulo = nullptr;
PyObject* pName = nullptr;
const char *scriptDirectoryName = "."; // NOTE: I changed the path for me
Py_InitializeEx(1); // NOTE: skip signal handlers being registered - for embedding
PyObject *sysPath = PySys_GetObject("path");
PyObject *path = PyUnicode_FromString(scriptDirectoryName);
int result = PyList_Insert(sysPath, 0, path);
if (result == 0 )//0 if ok, -1 if error
pName = PyUnicode_FromString("beep");//exportarXLS.py
modulo = PyImport_Import(pName);
Py_DECREF(path);
if (modulo)
// redirect segv handler here:
sig_t old = signal(SIGSEGV, catch_segv);
// record an environment to return to with siglongjmp
if (sigsetjmp(env, 1)) // returns 0 on setting up, 1 when called with siglongjmp(env, 1)
// handler called
Py_Finalize();
signal(SIGSEGV, old); // restore old handler
return 1; // return to caller
else
// this triggers a segv (for the test)
(reinterpret_cast<sig_t>(0))(1);
fExportar = PyObject_GetAttrString(modulo, "beep");//it crahs here
Py_DECREF(modulo);
if (fExportar)
//call the function
signal(SIGSEGV, old); // restore old handler
else
PyErr_Print();
Py_Finalize();
return 0; // return success.
int main(int argc, char **argv)
return myFunction();
Sorry. I have edited my question because it only crashes when I run the function under my Qt project. Running under yor code I get 1 if all ok or 0 if any error, but never crashes. But only if I run that code like a isolated project ( I have tried it under CodeBlocks) but if I adapt your code to my function under my Qt project it crashed too. Sorry because I forgot to say that I was under Qt porject and looks like it is important
– user3733164
Mar 29 at 11:09
That changes things significantly. From what I understand PyQt embeds it's own copies of the Qt libraries inside itself. You also have copies of the Qt Libraries in the application. This is unlikely to work. Check the output from the command line if you run the app directly (application.app/Contents/MacOS/application
to run it directly).
– Petesh
Mar 29 at 11:37
I'd recommend swapping fromPyQt
toPySide2
, which should use the same Qt as you have on the system. This should avoid the crashing problem
– Petesh
Mar 29 at 11:38
add a comment
|
This problem sounds familiar and I even can sort of reproduce it with your code:
If you call myFunction() more than once, what happens is that you import your modules more than once. According to the Docs this might cause issues:
"Some extensions may not work properly if their initialization routine
is called more than once; this can happen if an application calls
Py_Initialize() and Py_Finalize() more than once."
https://docs.python.org/2/c-api/init.html
So if that is the case in your app, a workaround is to initialize the Python Interpreter only once:
#include <iostream>
#include <Python/Python.h>
void myFuncion()
PyObject* fExportar = nullptr;
PyObject* modulo = nullptr;
PyObject* pName = nullptr;
const char *scriptDirectoryName = "path/of/my/pyfile";
PyObject *sysPath = PySys_GetObject("path");
PyObject *path = PyUnicode_FromString(scriptDirectoryName);
int result = PyList_Insert(sysPath, 0, path);
if (result == 0 )//0 if ok, -1 if error
pName = PyUnicode_FromString("exportarXLS");//exportarXLS.py
modulo = PyImport_Import(pName);
Py_DECREF(path);
if (modulo)
fExportar = PyObject_GetAttrString(modulo, "exportar");//it crahs here
Py_DECREF(modulo);
if (fExportar)
//call the function
else
PyErr_Print();
int main(int argc, const char * argv[])
Py_Initialize();
myFuncion();
myFuncion();
// what ever
Py_Finalize();
return 0;
EDIT: "I even can sort of reproduce it" meaning I can get it to crash, on a different line, though, by importing numpy.
add a comment
|
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/4.0/"u003ecc by-sa 4.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55394620%2fhow-to-avoid-segmentation-fault-when-calling-python-scripts-in-qt-project%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
3 Answers
3
active
oldest
votes
3 Answers
3
active
oldest
votes
active
oldest
votes
active
oldest
votes
Duck tape solution :
void signal_handler(int signal)
std::cout << "Usefull information" std::endl;
exit(1);
...
std::signal(SIGSEGV, signal_handler);
Doc : https://en.cppreference.com/w/cpp/utility/program/signal
I think this kind of solution should be used only in debug
add a comment
|
Duck tape solution :
void signal_handler(int signal)
std::cout << "Usefull information" std::endl;
exit(1);
...
std::signal(SIGSEGV, signal_handler);
Doc : https://en.cppreference.com/w/cpp/utility/program/signal
I think this kind of solution should be used only in debug
add a comment
|
Duck tape solution :
void signal_handler(int signal)
std::cout << "Usefull information" std::endl;
exit(1);
...
std::signal(SIGSEGV, signal_handler);
Doc : https://en.cppreference.com/w/cpp/utility/program/signal
I think this kind of solution should be used only in debug
Duck tape solution :
void signal_handler(int signal)
std::cout << "Usefull information" std::endl;
exit(1);
...
std::signal(SIGSEGV, signal_handler);
Doc : https://en.cppreference.com/w/cpp/utility/program/signal
I think this kind of solution should be used only in debug
answered Mar 28 at 10:10
Martin MorterolMartin Morterol
1,1401 gold badge2 silver badges8 bronze badges
1,1401 gold badge2 silver badges8 bronze badges
add a comment
|
add a comment
|
It would be best to deal with the problem by finding out the underlying cause of the SEGV as the state of your application could be seriously damaged by it being triggered.
If you want to attempt to catch the SEGV in a semi-structured manner then you can use something like the sample code, which uses sigsetjmp
and siglongjmp
:
#include <python3.7m/Python.h> // That's my python
#include <setjmp.h>
#include <signal.h>
static sigjmp_buf env;
static void
catch_segv(int func)
siglongjmp(env, 1);
int myFunction()
PyObject* fExportar = nullptr;
PyObject* modulo = nullptr;
PyObject* pName = nullptr;
const char *scriptDirectoryName = "."; // NOTE: I changed the path for me
Py_InitializeEx(1); // NOTE: skip signal handlers being registered - for embedding
PyObject *sysPath = PySys_GetObject("path");
PyObject *path = PyUnicode_FromString(scriptDirectoryName);
int result = PyList_Insert(sysPath, 0, path);
if (result == 0 )//0 if ok, -1 if error
pName = PyUnicode_FromString("beep");//exportarXLS.py
modulo = PyImport_Import(pName);
Py_DECREF(path);
if (modulo)
// redirect segv handler here:
sig_t old = signal(SIGSEGV, catch_segv);
// record an environment to return to with siglongjmp
if (sigsetjmp(env, 1)) // returns 0 on setting up, 1 when called with siglongjmp(env, 1)
// handler called
Py_Finalize();
signal(SIGSEGV, old); // restore old handler
return 1; // return to caller
else
// this triggers a segv (for the test)
(reinterpret_cast<sig_t>(0))(1);
fExportar = PyObject_GetAttrString(modulo, "beep");//it crahs here
Py_DECREF(modulo);
if (fExportar)
//call the function
signal(SIGSEGV, old); // restore old handler
else
PyErr_Print();
Py_Finalize();
return 0; // return success.
int main(int argc, char **argv)
return myFunction();
Sorry. I have edited my question because it only crashes when I run the function under my Qt project. Running under yor code I get 1 if all ok or 0 if any error, but never crashes. But only if I run that code like a isolated project ( I have tried it under CodeBlocks) but if I adapt your code to my function under my Qt project it crashed too. Sorry because I forgot to say that I was under Qt porject and looks like it is important
– user3733164
Mar 29 at 11:09
That changes things significantly. From what I understand PyQt embeds it's own copies of the Qt libraries inside itself. You also have copies of the Qt Libraries in the application. This is unlikely to work. Check the output from the command line if you run the app directly (application.app/Contents/MacOS/application
to run it directly).
– Petesh
Mar 29 at 11:37
I'd recommend swapping fromPyQt
toPySide2
, which should use the same Qt as you have on the system. This should avoid the crashing problem
– Petesh
Mar 29 at 11:38
add a comment
|
It would be best to deal with the problem by finding out the underlying cause of the SEGV as the state of your application could be seriously damaged by it being triggered.
If you want to attempt to catch the SEGV in a semi-structured manner then you can use something like the sample code, which uses sigsetjmp
and siglongjmp
:
#include <python3.7m/Python.h> // That's my python
#include <setjmp.h>
#include <signal.h>
static sigjmp_buf env;
static void
catch_segv(int func)
siglongjmp(env, 1);
int myFunction()
PyObject* fExportar = nullptr;
PyObject* modulo = nullptr;
PyObject* pName = nullptr;
const char *scriptDirectoryName = "."; // NOTE: I changed the path for me
Py_InitializeEx(1); // NOTE: skip signal handlers being registered - for embedding
PyObject *sysPath = PySys_GetObject("path");
PyObject *path = PyUnicode_FromString(scriptDirectoryName);
int result = PyList_Insert(sysPath, 0, path);
if (result == 0 )//0 if ok, -1 if error
pName = PyUnicode_FromString("beep");//exportarXLS.py
modulo = PyImport_Import(pName);
Py_DECREF(path);
if (modulo)
// redirect segv handler here:
sig_t old = signal(SIGSEGV, catch_segv);
// record an environment to return to with siglongjmp
if (sigsetjmp(env, 1)) // returns 0 on setting up, 1 when called with siglongjmp(env, 1)
// handler called
Py_Finalize();
signal(SIGSEGV, old); // restore old handler
return 1; // return to caller
else
// this triggers a segv (for the test)
(reinterpret_cast<sig_t>(0))(1);
fExportar = PyObject_GetAttrString(modulo, "beep");//it crahs here
Py_DECREF(modulo);
if (fExportar)
//call the function
signal(SIGSEGV, old); // restore old handler
else
PyErr_Print();
Py_Finalize();
return 0; // return success.
int main(int argc, char **argv)
return myFunction();
Sorry. I have edited my question because it only crashes when I run the function under my Qt project. Running under yor code I get 1 if all ok or 0 if any error, but never crashes. But only if I run that code like a isolated project ( I have tried it under CodeBlocks) but if I adapt your code to my function under my Qt project it crashed too. Sorry because I forgot to say that I was under Qt porject and looks like it is important
– user3733164
Mar 29 at 11:09
That changes things significantly. From what I understand PyQt embeds it's own copies of the Qt libraries inside itself. You also have copies of the Qt Libraries in the application. This is unlikely to work. Check the output from the command line if you run the app directly (application.app/Contents/MacOS/application
to run it directly).
– Petesh
Mar 29 at 11:37
I'd recommend swapping fromPyQt
toPySide2
, which should use the same Qt as you have on the system. This should avoid the crashing problem
– Petesh
Mar 29 at 11:38
add a comment
|
It would be best to deal with the problem by finding out the underlying cause of the SEGV as the state of your application could be seriously damaged by it being triggered.
If you want to attempt to catch the SEGV in a semi-structured manner then you can use something like the sample code, which uses sigsetjmp
and siglongjmp
:
#include <python3.7m/Python.h> // That's my python
#include <setjmp.h>
#include <signal.h>
static sigjmp_buf env;
static void
catch_segv(int func)
siglongjmp(env, 1);
int myFunction()
PyObject* fExportar = nullptr;
PyObject* modulo = nullptr;
PyObject* pName = nullptr;
const char *scriptDirectoryName = "."; // NOTE: I changed the path for me
Py_InitializeEx(1); // NOTE: skip signal handlers being registered - for embedding
PyObject *sysPath = PySys_GetObject("path");
PyObject *path = PyUnicode_FromString(scriptDirectoryName);
int result = PyList_Insert(sysPath, 0, path);
if (result == 0 )//0 if ok, -1 if error
pName = PyUnicode_FromString("beep");//exportarXLS.py
modulo = PyImport_Import(pName);
Py_DECREF(path);
if (modulo)
// redirect segv handler here:
sig_t old = signal(SIGSEGV, catch_segv);
// record an environment to return to with siglongjmp
if (sigsetjmp(env, 1)) // returns 0 on setting up, 1 when called with siglongjmp(env, 1)
// handler called
Py_Finalize();
signal(SIGSEGV, old); // restore old handler
return 1; // return to caller
else
// this triggers a segv (for the test)
(reinterpret_cast<sig_t>(0))(1);
fExportar = PyObject_GetAttrString(modulo, "beep");//it crahs here
Py_DECREF(modulo);
if (fExportar)
//call the function
signal(SIGSEGV, old); // restore old handler
else
PyErr_Print();
Py_Finalize();
return 0; // return success.
int main(int argc, char **argv)
return myFunction();
It would be best to deal with the problem by finding out the underlying cause of the SEGV as the state of your application could be seriously damaged by it being triggered.
If you want to attempt to catch the SEGV in a semi-structured manner then you can use something like the sample code, which uses sigsetjmp
and siglongjmp
:
#include <python3.7m/Python.h> // That's my python
#include <setjmp.h>
#include <signal.h>
static sigjmp_buf env;
static void
catch_segv(int func)
siglongjmp(env, 1);
int myFunction()
PyObject* fExportar = nullptr;
PyObject* modulo = nullptr;
PyObject* pName = nullptr;
const char *scriptDirectoryName = "."; // NOTE: I changed the path for me
Py_InitializeEx(1); // NOTE: skip signal handlers being registered - for embedding
PyObject *sysPath = PySys_GetObject("path");
PyObject *path = PyUnicode_FromString(scriptDirectoryName);
int result = PyList_Insert(sysPath, 0, path);
if (result == 0 )//0 if ok, -1 if error
pName = PyUnicode_FromString("beep");//exportarXLS.py
modulo = PyImport_Import(pName);
Py_DECREF(path);
if (modulo)
// redirect segv handler here:
sig_t old = signal(SIGSEGV, catch_segv);
// record an environment to return to with siglongjmp
if (sigsetjmp(env, 1)) // returns 0 on setting up, 1 when called with siglongjmp(env, 1)
// handler called
Py_Finalize();
signal(SIGSEGV, old); // restore old handler
return 1; // return to caller
else
// this triggers a segv (for the test)
(reinterpret_cast<sig_t>(0))(1);
fExportar = PyObject_GetAttrString(modulo, "beep");//it crahs here
Py_DECREF(modulo);
if (fExportar)
//call the function
signal(SIGSEGV, old); // restore old handler
else
PyErr_Print();
Py_Finalize();
return 0; // return success.
int main(int argc, char **argv)
return myFunction();
answered Mar 28 at 12:35
PeteshPetesh
73k3 gold badges76 silver badges98 bronze badges
73k3 gold badges76 silver badges98 bronze badges
Sorry. I have edited my question because it only crashes when I run the function under my Qt project. Running under yor code I get 1 if all ok or 0 if any error, but never crashes. But only if I run that code like a isolated project ( I have tried it under CodeBlocks) but if I adapt your code to my function under my Qt project it crashed too. Sorry because I forgot to say that I was under Qt porject and looks like it is important
– user3733164
Mar 29 at 11:09
That changes things significantly. From what I understand PyQt embeds it's own copies of the Qt libraries inside itself. You also have copies of the Qt Libraries in the application. This is unlikely to work. Check the output from the command line if you run the app directly (application.app/Contents/MacOS/application
to run it directly).
– Petesh
Mar 29 at 11:37
I'd recommend swapping fromPyQt
toPySide2
, which should use the same Qt as you have on the system. This should avoid the crashing problem
– Petesh
Mar 29 at 11:38
add a comment
|
Sorry. I have edited my question because it only crashes when I run the function under my Qt project. Running under yor code I get 1 if all ok or 0 if any error, but never crashes. But only if I run that code like a isolated project ( I have tried it under CodeBlocks) but if I adapt your code to my function under my Qt project it crashed too. Sorry because I forgot to say that I was under Qt porject and looks like it is important
– user3733164
Mar 29 at 11:09
That changes things significantly. From what I understand PyQt embeds it's own copies of the Qt libraries inside itself. You also have copies of the Qt Libraries in the application. This is unlikely to work. Check the output from the command line if you run the app directly (application.app/Contents/MacOS/application
to run it directly).
– Petesh
Mar 29 at 11:37
I'd recommend swapping fromPyQt
toPySide2
, which should use the same Qt as you have on the system. This should avoid the crashing problem
– Petesh
Mar 29 at 11:38
Sorry. I have edited my question because it only crashes when I run the function under my Qt project. Running under yor code I get 1 if all ok or 0 if any error, but never crashes. But only if I run that code like a isolated project ( I have tried it under CodeBlocks) but if I adapt your code to my function under my Qt project it crashed too. Sorry because I forgot to say that I was under Qt porject and looks like it is important
– user3733164
Mar 29 at 11:09
Sorry. I have edited my question because it only crashes when I run the function under my Qt project. Running under yor code I get 1 if all ok or 0 if any error, but never crashes. But only if I run that code like a isolated project ( I have tried it under CodeBlocks) but if I adapt your code to my function under my Qt project it crashed too. Sorry because I forgot to say that I was under Qt porject and looks like it is important
– user3733164
Mar 29 at 11:09
That changes things significantly. From what I understand PyQt embeds it's own copies of the Qt libraries inside itself. You also have copies of the Qt Libraries in the application. This is unlikely to work. Check the output from the command line if you run the app directly (
application.app/Contents/MacOS/application
to run it directly).– Petesh
Mar 29 at 11:37
That changes things significantly. From what I understand PyQt embeds it's own copies of the Qt libraries inside itself. You also have copies of the Qt Libraries in the application. This is unlikely to work. Check the output from the command line if you run the app directly (
application.app/Contents/MacOS/application
to run it directly).– Petesh
Mar 29 at 11:37
I'd recommend swapping from
PyQt
to PySide2
, which should use the same Qt as you have on the system. This should avoid the crashing problem– Petesh
Mar 29 at 11:38
I'd recommend swapping from
PyQt
to PySide2
, which should use the same Qt as you have on the system. This should avoid the crashing problem– Petesh
Mar 29 at 11:38
add a comment
|
This problem sounds familiar and I even can sort of reproduce it with your code:
If you call myFunction() more than once, what happens is that you import your modules more than once. According to the Docs this might cause issues:
"Some extensions may not work properly if their initialization routine
is called more than once; this can happen if an application calls
Py_Initialize() and Py_Finalize() more than once."
https://docs.python.org/2/c-api/init.html
So if that is the case in your app, a workaround is to initialize the Python Interpreter only once:
#include <iostream>
#include <Python/Python.h>
void myFuncion()
PyObject* fExportar = nullptr;
PyObject* modulo = nullptr;
PyObject* pName = nullptr;
const char *scriptDirectoryName = "path/of/my/pyfile";
PyObject *sysPath = PySys_GetObject("path");
PyObject *path = PyUnicode_FromString(scriptDirectoryName);
int result = PyList_Insert(sysPath, 0, path);
if (result == 0 )//0 if ok, -1 if error
pName = PyUnicode_FromString("exportarXLS");//exportarXLS.py
modulo = PyImport_Import(pName);
Py_DECREF(path);
if (modulo)
fExportar = PyObject_GetAttrString(modulo, "exportar");//it crahs here
Py_DECREF(modulo);
if (fExportar)
//call the function
else
PyErr_Print();
int main(int argc, const char * argv[])
Py_Initialize();
myFuncion();
myFuncion();
// what ever
Py_Finalize();
return 0;
EDIT: "I even can sort of reproduce it" meaning I can get it to crash, on a different line, though, by importing numpy.
add a comment
|
This problem sounds familiar and I even can sort of reproduce it with your code:
If you call myFunction() more than once, what happens is that you import your modules more than once. According to the Docs this might cause issues:
"Some extensions may not work properly if their initialization routine
is called more than once; this can happen if an application calls
Py_Initialize() and Py_Finalize() more than once."
https://docs.python.org/2/c-api/init.html
So if that is the case in your app, a workaround is to initialize the Python Interpreter only once:
#include <iostream>
#include <Python/Python.h>
void myFuncion()
PyObject* fExportar = nullptr;
PyObject* modulo = nullptr;
PyObject* pName = nullptr;
const char *scriptDirectoryName = "path/of/my/pyfile";
PyObject *sysPath = PySys_GetObject("path");
PyObject *path = PyUnicode_FromString(scriptDirectoryName);
int result = PyList_Insert(sysPath, 0, path);
if (result == 0 )//0 if ok, -1 if error
pName = PyUnicode_FromString("exportarXLS");//exportarXLS.py
modulo = PyImport_Import(pName);
Py_DECREF(path);
if (modulo)
fExportar = PyObject_GetAttrString(modulo, "exportar");//it crahs here
Py_DECREF(modulo);
if (fExportar)
//call the function
else
PyErr_Print();
int main(int argc, const char * argv[])
Py_Initialize();
myFuncion();
myFuncion();
// what ever
Py_Finalize();
return 0;
EDIT: "I even can sort of reproduce it" meaning I can get it to crash, on a different line, though, by importing numpy.
add a comment
|
This problem sounds familiar and I even can sort of reproduce it with your code:
If you call myFunction() more than once, what happens is that you import your modules more than once. According to the Docs this might cause issues:
"Some extensions may not work properly if their initialization routine
is called more than once; this can happen if an application calls
Py_Initialize() and Py_Finalize() more than once."
https://docs.python.org/2/c-api/init.html
So if that is the case in your app, a workaround is to initialize the Python Interpreter only once:
#include <iostream>
#include <Python/Python.h>
void myFuncion()
PyObject* fExportar = nullptr;
PyObject* modulo = nullptr;
PyObject* pName = nullptr;
const char *scriptDirectoryName = "path/of/my/pyfile";
PyObject *sysPath = PySys_GetObject("path");
PyObject *path = PyUnicode_FromString(scriptDirectoryName);
int result = PyList_Insert(sysPath, 0, path);
if (result == 0 )//0 if ok, -1 if error
pName = PyUnicode_FromString("exportarXLS");//exportarXLS.py
modulo = PyImport_Import(pName);
Py_DECREF(path);
if (modulo)
fExportar = PyObject_GetAttrString(modulo, "exportar");//it crahs here
Py_DECREF(modulo);
if (fExportar)
//call the function
else
PyErr_Print();
int main(int argc, const char * argv[])
Py_Initialize();
myFuncion();
myFuncion();
// what ever
Py_Finalize();
return 0;
EDIT: "I even can sort of reproduce it" meaning I can get it to crash, on a different line, though, by importing numpy.
This problem sounds familiar and I even can sort of reproduce it with your code:
If you call myFunction() more than once, what happens is that you import your modules more than once. According to the Docs this might cause issues:
"Some extensions may not work properly if their initialization routine
is called more than once; this can happen if an application calls
Py_Initialize() and Py_Finalize() more than once."
https://docs.python.org/2/c-api/init.html
So if that is the case in your app, a workaround is to initialize the Python Interpreter only once:
#include <iostream>
#include <Python/Python.h>
void myFuncion()
PyObject* fExportar = nullptr;
PyObject* modulo = nullptr;
PyObject* pName = nullptr;
const char *scriptDirectoryName = "path/of/my/pyfile";
PyObject *sysPath = PySys_GetObject("path");
PyObject *path = PyUnicode_FromString(scriptDirectoryName);
int result = PyList_Insert(sysPath, 0, path);
if (result == 0 )//0 if ok, -1 if error
pName = PyUnicode_FromString("exportarXLS");//exportarXLS.py
modulo = PyImport_Import(pName);
Py_DECREF(path);
if (modulo)
fExportar = PyObject_GetAttrString(modulo, "exportar");//it crahs here
Py_DECREF(modulo);
if (fExportar)
//call the function
else
PyErr_Print();
int main(int argc, const char * argv[])
Py_Initialize();
myFuncion();
myFuncion();
// what ever
Py_Finalize();
return 0;
EDIT: "I even can sort of reproduce it" meaning I can get it to crash, on a different line, though, by importing numpy.
edited Mar 28 at 15:35
answered Mar 28 at 14:49
NicoLazzNicoLazz
846 bronze badges
846 bronze badges
add a comment
|
add a comment
|
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55394620%2fhow-to-avoid-segmentation-fault-when-calling-python-scripts-in-qt-project%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Not able to reproduce a crash for this. If the module fails to load, I don't get a crash, I just get a NULL. The duct tape workaround doesn't really help here as it's most likely an environment issue that's triggering the problem which you need to get to the root of. You can try with the environment variable
PYTHONVERBOSE
to see the difference between loading via C++ and loading from python3 directly to see if there's a difference there. I'll give you an option for an 'in the event of a SEGV', but you need to determine the why of it.– Petesh
Mar 28 at 12:09