473,657 Members | 2,693 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Catching SystemExit in C API code when embedding Python?

Hi all!

I am embedding Python into a GUI application in a way that the GUI is
scriptable using Python.

Now I have come to a problem that when the user puts a "sys.exit(0 )"
into his script to end the script, not only the script is terminated,
but also the GUI application itself. This is not the intended behaviour.

As in Python itself you can catch SystemExit, I think this should be
the way to go. But how do I catch this exception from within the C API?

Thanks in advance for any hints.

--
Stefan Bellon
Aug 2 '07 #1
5 3806
Stefan Bellon wrote:
Hi all!

I am embedding Python into a GUI application in a way that the GUI is
scriptable using Python.

Now I have come to a problem that when the user puts a "sys.exit(0 )"
into his script to end the script, not only the script is terminated,
but also the GUI application itself. This is not the intended behaviour.

As in Python itself you can catch SystemExit, I think this should be
the way to go. But how do I catch this exception from within the C API?

Thanks in advance for any hints.
Have a look at the following doc page for handling exceptions with the C
api:

http://docs.python.org/api/exceptionHandling.html

Also, here is some sample code that will catch system exit exceptions:

//Call python code
....
//Check for system exit exception
if(PyErr_Occurr ed()) {
if(PyErr_Except ionMatches(PyEx c_SystemExit)) {
//handle system exit
PyErr_Clear();
} else {
PyErr_Print();
}
}
Aug 2 '07 #2
First of all, I'm sorry to followup my own posting, but I can add a few
things ...

On Thu, 02 Aug, Stefan Bellon wrote:
As in Python itself you can catch SystemExit, I think this should be
the way to go. But how do I catch this exception from within the C
API?
I now installed an exception hook in sys.excepthook on the C side. And
indeed, it gets called whenever an exception is raised ... but not when
SystemExit is raised. And indeed, in PyErr_PrintEx in pythonrun.c I
found the following:

hook = PySys_GetObject ("excepthook ");
if (hook) {
PyObject *args = PyTuple_Pack(3,
exception, v ? v : Py_None, tb ? tb : Py_None);
PyObject *result = PyEval_CallObje ct(hook, args);
if (result == NULL) {
PyObject *exception2, *v2, *tb2;
if (PyErr_Exceptio nMatches(PyExc_ SystemExit)) {
handle_system_e xit();
}

But ... then my original question becomes even stronger: How do I
"catch" a SystemExit when embedding Python and not wanting that a
script with sys.exit just terminates the whole application?

--
Stefan Bellon
Aug 2 '07 #3
On Thu, 02 Aug, Farshid Lashkari wrote:
Also, here is some sample code that will catch system exit exceptions:

//Call python code
...
//Check for system exit exception
if(PyErr_Occurr ed()) {
if(PyErr_Except ionMatches(PyEx c_SystemExit)) {
//handle system exit
PyErr_Clear();
} else {
PyErr_Print();
}
}
Thanks for your hints ...

The interesting part is "Call python code". In my example this is done
with PyRun_SimpleStr ing which does not return if an exception is not
handled but raised "out of" the interpreter. So I am unsure of what you
mean with "Call python code".

When installing an excepthook (see my other posting), then I can indeed
catch all exceptions ... except for SystemExit which is the one I'm
after.

--
Stefan Bellon
Aug 2 '07 #4
Stefan Bellon wrote:
Thanks for your hints ...

The interesting part is "Call python code". In my example this is done
with PyRun_SimpleStr ing which does not return if an exception is not
handled but raised "out of" the interpreter. So I am unsure of what you
mean with "Call python code".

When installing an excepthook (see my other posting), then I can indeed
catch all exceptions ... except for SystemExit which is the one I'm
after.
You cannot use PyRun_SimpleStr ing, since it will automatically print and
clear the error. You will need to use PyRun_String instead.
Aug 2 '07 #5
On Thu, 02 Aug, Farshid Lashkari wrote:
You cannot use PyRun_SimpleStr ing, since it will automatically print
and clear the error. You will need to use PyRun_String instead.
Thanks, that helps a lot!

--
Stefan Bellon
Aug 2 '07 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
4983
by: Olli Piepponen | last post by:
Hi, I'm having a little problem catching keystrokes under Windows. I did a little research and found that with mscvrt.getch() one can cath a single key that is pressed. However this doesn't work when the program is run on the backround and not as the primary task. What I would like to have is a same sort of function that would also work when the program is being run on the background. I'm trying to implement a program that would listen...
1
1832
by: Tommy Nordgren | last post by:
I want to write an application that embeds and extends (at least) the Python and Perl interpreters. Now i want to find as much as possible about the Python tools used for extending and embedding Python. To be more specific: My app should: 1. Parse an input file. 2. Call a script in some scripting language, to generate an output file, for example in C++. For task 2 I need to call an embedded interpreter, and also provide call backs from...
17
19654
by: seberino | last post by:
How can a proprietary software developer protect their Python code? People often ask me about obfuscating Python bytecode. They don't want people to easily decompile their proprietary Python app. I suppose another idea is to rewrite entire Python app in C if compiled C code is harder to decompile. Any ideas?
0
1252
by: Steven Bethard | last post by:
I have an optparse-like module and though I have a full unittest-style suite of tests for it, I'd also like to be able to run doctest on the documentation to make sure my examples all work. However, I see that doctest (1) doesn't capture anything from sys.stderr, and (2) unlike the normal interpreter, generates a traceback for SystemExit. Here's what some of my tests look like and the doctest output I get:: ========== in my...
5
2310
by: Avi Kak | last post by:
Folks, Does regular expression processing in Python allow for executable code to be embedded inside a regular expression? For example, in Perl the following two statements $regex = qr/hello(?{print "saw hello\n"})mello(?{print "saw mello\n"})/; "jellohellomello" =~ /$regex/;
2
2343
by: p.lavarre | last post by:
From: http://docs.python.org/lib/doctest-soapbox.html ... Can I somehow tell doctest that it's time to quit? I ask because not all doctest examples are created equal. Some failures are catastrophic, making all subsequent failures at least uninteresting, and maybe painfully slow. Other failures are negligible, making the print of any subsequent failure valuable. So sys.exit() doesn't do what I mean: it raises SystemExit, but doctest
3
11339
by: Will McGugan | last post by:
Hi, Is there any difference between calling sys.exit() and raise SystemExit? Should I prefer one over the other? Regards, Will McGugan -- blog: http://www.willmcgugan.com
2
2316
by: bappai | last post by:
Hello, I am trying to actually call a GUI from my C++ code which would have buttons and therefore can call functions from C++ again, ie extend the C++ code also. I am faced with a peculiar problem. I actually tried out an embedding code (downloaded from the net) which actually calls any function which has a text display but when I try to call any code which opens cleanly in python prompt it crashes. To make matters more concrete let me...
3
3278
by: john | last post by:
I wrapped some fortran code using F2PY and need to be able to catch fortran runtime errors to run the following: # "grid" is a wrapped fortran module # no runtime errors incurred when run with the correct inputs for filetype #------------------------------- def readGrid( self, coord='xyz' ): mg = ( '.FALSE.', '.TRUE.' ) form = ( 'FORMATTED', 'UNFORMATTED' )
0
8737
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8509
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8610
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7345
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
4168
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4327
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2735
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1967
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1730
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.