开发者

How to stop a code running due to an input error without causing the GUI from crashing

开发者 https://www.devze.com 2023-04-11 06:04 出处:网络
I had a program developed in Python (2.7 & 3.2) that reads three files and generates some code based on those files.In the code, I had several input file checks to capture any input errors by the

I had a program developed in Python (2.7 & 3.2) that reads three files and generates some code based on those files. In the code, I had several input file checks to capture any input errors by the user. If the program catches an input error, I used os.sys.exit() command to stop processing and issue an error message. I was primarily using IDLE for the process and this worked fine.

Now I have developed a GUI for the program for deployment using PYQT4. The user uses the GUI to input all the necessary input files and conditions and then the GUI calls the earlier code I generated with the necessary arguments.

However, I am finding that if the user makes an error in the input files, when the earlier code catches those errors and the os.sys.exit() is executed, the GUI itself is shutdown completely; which is not good.

I introduced the same checks on the input files into the GUI, so if those are caught, they are treated within the GUI and not by the code. But there are certain processing checks that happen inside the code that the GUI does not have access to them.开发者_如何学Python

The Question: Is there a way to make the called code stop from running, print an error message (to a log file for example; which I already use) without causing the GUI to quit altogether?

Thanks,

note: The code is too large at this point for me to integrate it into the GUI as a class.


I assume you can not or prefer not to change your CLI programs and instead wish to catch the exception raised by sys.exit instead in the GUI. Here is how:

import os
try:
   os.sys.exit()
except SystemExit as err:
   print('Caught ya')


Have you tried handling exceptions in python.

try:
   #some code here
except Exception:
   print 'Something bad happened'

Better try catching specific exceptions. List of built-in exceptions http://docs.python.org/library/exceptions.html#bltin-exceptions

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号