I'm doing some very simple PySide (and PyQt) tutorials in IPython. One tutorial just creates a window with some sliders to demonstrate slots and signals.
When I close the window of the running demo application, I see this error:
An exception has occurred, use %tb to see the full traceback.
SystemExit: 0
To exit: use 'exit', 'quit', or Ctrl-D.
So I run %tb and get this:
SystemExit Traceback (most recent call last)
/Workspaces/scratch/<ipython-input-1-88966dcfb499> in <module>()
33
34 if __name__ == "__main__":
---> 35 main()
/Workspaces/scratch/<ipython-input-1-88966dcfb499> in main()
29 w.show()
30 app.exec_()
---> 31 sys.exit(0)
32
33
SystemExit: 0
If I try to execute my code again, I get this:
RuntimeError: A QApplication instance already exists.
In case it helps, here my code:
from PySide.QtCore import *
from PySide.QtGui import *
import sys
class MyWindow(QWidget):
def __init__(self):
QWidget.__init__(self, None)
vbox = QVBoxLayout(self)
self.slider1 = QSlider(Qt.Horizontal)
self.slider1.setRange(0, 99)
self.slider1.setValue(0)
vbox.addWidget(self.slider1)
self.slider2 = QSlider(Qt.Horizontal)
self.slider2.setRange(0, 99)
self.slider2.setValue(99)
vbox.addWidget(self.slider2)
self.slider1.valueChanged.connect(self.slider2Changed)
def slider2Changed(self, position):
self.slider2.setValue(self.slider2.maximum() - position)
def main():
app = QApplication(sys.argv)
w = MyWindow()
w.show()
app.exec_()
sys.exit(0)
if __name__ == "__main__":
main()
I do not have errors when running the code using python:
python myexample.py
This error only happens when I run the code in an IPython (including a notebook or the qtconsole or the regular ipython terminal).
UPDATE: My main problem is that I cannot run the application again quickly and easily. If I try to run my code again, I get this:
RuntimeError: A QApplication instance already exists.
That kills the fast, interactive nature of IPython :(
This answer is thanks to Matthias BUSSONNIER from the ipython-users mailing list.
When I close the window of the running demo application, I see this error:
An exception has occurred, use %tb to see the full traceback.
SystemExit: 0
Just don't use sys.exit(0) as you are not exiting python, but still running IPython.
Add it back if you wish to run your app from a (real) command line and have a return status.
If I try to execute my code again, I get this:
RuntimeError: A QApplication instance already exists.
This is a PySide Bug that they "won't fix" as they don't consider it a bug.
See https://github.com/ipython/ipython/issues/1124)
and http://bugs.pyside.org/show_bug.cgi?id=855
QApplication can only have one instance and quitting an app is
apparently not considered a reason sufficient enough do delete the
object...
You can use this code from above issues :
app=QtGui.QApplication.instance() # checks if QApplication already exists
if not app: # create QApplication if it doesnt exist
app = QtGui.QApplication(sys.argv)
This was a sufficient solution for my present needs.
What you need to do is to cause the QApplication to be deleted later as in:
app = QApplication(sys.argv)
app.aboutToQuit.connect(app.deleteLater)
Using this code you can rerun the application as many times as you want in IPython, or anywhere else and every time you close your qt application, the object will be deleted in python.
sys.exit just raises SystemExit to terminate the interperter.
ipython catches SysExit when it executes a script in interactive mode, so this isn't acutally an error but a feature of ipython do avoid the interactive interpreter from being shutdown when a script is executed, as that's not what you usually want in an interactive session.
According to https://github.com/spyder-ide/spyder/issues/4639,
First, check if the instance is already present, and either assign that, or make a new one:
if not QApplication.instance():
app = QApplication(sys.argv)
else:
app = QApplication.instance()
(This snippet is taken from the answer by #NotSoBrainy.)
Then, after the show() method:
QtWidgets.QApplication.setQuitOnLastWindowClosed(True)
app.exec_()
app.quit()
There’s no need for sys.exit().
This solved my issue, which was exactly the same.
Check if already an instance of QApplication is present or not as the error occurs when an instance is already running and you are trying to create a new one.
if not QtWidgets.QApplication.instance():
app = QtWidgets.QApplication(sys.argv)
else:
app = QtWidgets.QApplication.instance()
Related
I am working on topic inference that will require to load a previously saved model.
However, I got a pickle error that says
Traceback (most recent call last):
File "topic_inference.py", line 35, in <module>
model_for_inference = gensim.models.LdaModel.load(model_name, mmap = 'r')
File "topic_modeling/env/lib/python3.8/site-packages/gensim/models/ldamodel.py", line 1663, in load
result = super(LdaModel, cls).load(fname, *args, **kwargs)
File "topic_modeling/env/lib/python3.8/site-packages/gensim/utils.py", line 486, in load
obj = unpickle(fname)
File "topic_modeling/env/lib/python3.8/site-packages/gensim/utils.py", line 1461, in unpickle
return _pickle.load(f, encoding='latin1') # needed because loading from S3 doesn't support readline()
TypeError: __randomstate_ctor() takes from 0 to 1 positional arguments but 2 were given
The code I use to load the model is simply
gensim.models.LdaModel.load(model_name, mmap = 'r')
Here is the code that I use to create and save the model
model = gensim.models.ldamulticore.LdaMulticore(
corpus=comment_corpus,
id2word=key_word_dict, ## This is now a gensim.corpora.Dictionary Object, previously it was the .id2token attribute
chunksize=chunksize,
alpha='symmetric',
eta='auto',
iterations=iterations,
num_topics=num_topics,
passes=epochs,
eval_every=eval_every,
workers = 15,
minimum_probability= 0.0)
model.save(output_model)
where output_model doesn't have an extension like .model or .pkl
In the past, I tried the similar approach with the exception that I passed in a .id2token attribute under the gensim.corpora.Dictionary object instead of the full gensim.corpora.Dictionary to the id2word parameter when I created the model, and the method loads the model fine back then. I wonder if passing in a corpora.Dictionary will make a difference in the loading output...? Back that time, I was using regular python, but now I am using anaconda. However, all the versions of the packages are the same.
Another report of an error about __randomstate_ctor (at https://github.com/numpy/numpy/issues/14210) suggests the problem may be related to numpy object pickling.
Is there a chance that the configuration where your load is failing is using a later version of numpy than when the save occurred? Could you try, at least temporarily, rolling back to some older numpy (that's still sufficient for whatever Gensim you're using) to see if it helps?
If you find any load that works, even in a suboptimal config, you might be able to null-out whatever random-related objects are causing the problem and re-save, then having a saved version that loads better in your truly-desired configuration. Then, if the random-related objects truly needed after reload, it may be possible to manually re-constitute them. (I haven't looked into this yet, but if you find any workaround allowing a load, but then aren't sure what to manually null/rebuild, I could take a closer look.)
I am trying to write a simple function to test why numba.cuda isn't working. The function should set a variable to a fixed value. When I call the function, it seems to compile, but nothing happens. I added, that it should raise an exception, just to see, that it gets called, but again nothing happens. I don't get any kind of exception to give me a hint, why it is not working.
Function:
from numba import cuda
#cuda.jit # also tried it with brackets: #cuda.jit()
def cuda_func(out):
out = 1
raise NameError('MyException')
I call the funtction like this:
>>> import Cuda_Class
>>> a = 0
>>> Cuda_Class.cuda_func[1, 1](a)
>>> a
0
numba.cuda.is_available returns True.
I am working inside a miniconda environment and had some trouble with installing cuda. I accidentally installed multiple versions, so I had to purge everything, and installed cuda 10.2 in my base environment. In the conda environment I installed the cudatoolkit (10.2.89).
I set CUDA_HOME to /usr/local/cuda-10.2. So nvcc --version gives me the right version. So the compiler is accessible.
NUMBA_CUDA_DRIVER should lead to cudalib.so, which I had trouble finding. I did not manually install the nvidia driver, it was installed in combination with cuda. I found cudalib.so under /usr/local/cuda-10.2/targets/x86_64-linux/lib/stubs/libcuda.so. There was no other file named libcuda.so, only libcuda.so.7. However, even before I set NUMBA_CUDA_DRIVER and it was empty, the behavior was exactly the same. No reaction, no exceptions. It looks as if the function would be called correctly, but nothing happens.
The only idea I have left is, that maybe it is a problem, that libcuda.so is in a "stubs" folder?
The first comment solved my problem:
I tried to change the value of an immutable Integer.
Although raise is supported by numba.cuda, apparently exceptions are not supported.
Neither of those mistakes lead to an error message.
Changing "out" to an array and manipulating the first value works.
filename and line number of python script
I need to print the current filename, function and line number in a Cython script. The proposed solutions only work for .py script and they do NOT work for Cython script.
Thank you
This is a pretty unsatisfactory work-round, but I suspect it's probably (close to) the best you can do.
Cython generates debugging info when an exception is raised, therefore you need to raise and catch and exception to get access to this info
import sys
import traceback
def f():
# code ...
try:
raise RuntimeError() # get information about this line
except RuntimeError:
print(traceback.extract_tb(sys.exc_info()[2],limit=1))
# ... more code
Note that you can't attempt to save duplication by putting this all in a "get_debug_info" function and then looking further up the stack trace - Cython only generates the stack frame for a function as the exception propagates up the stack so if you catch the exception then you can't see any Cython frames above it.
invalid command name in tcl while running my tcl script for new protocol in ns2 it shows error as:
num_nodes is set 108
invalid command name “Agent/HEBM”
while executing
“Agent/HEBM set radius_2”
(file “balance.tcl” line31)
please, reply as soon as possible, it will be very helpful to implement my project.
It is because tkinter window closed but other processes related to it are still running. To avoid this, put try and except wherever the error is occurring in your code. To avoid the error, do this whenever the error function is called:
import sys
...
try: the_function()
except: sys.exit(1)
Fell free to comment in case of more detail requirement or any error if occurred.
I am trying to build a general exception handler for a swing application as described here: http://www.javaspecialists.eu/archive/Issue081.html
I work in jython (python syntax getting compiled to java and executed). My code looks roughly like this (updated):
def launcher(func):
class launcherThread(Runnable):
def __init__(self):
super(launcherThread, self).__init__()
def run(self):
func()
#trying to get the name which can be used to instantiate this in java
cls = ExceptionGroup().getClass()
fullName = cls.__module__ + '.' + cls.__name__
System.setProperty("sun.awt.exception.handler", fullName)
Thread(ExceptionGroup(), launcherThread(), 'Cross ExceptionHandlerThread').start()
class ExceptionGroup(ThreadGroup):
def __init__(self):
super(ExceptionGroup, self).__init__("HardenedGroup")
def uncaughtException(self, thread, exception):
#make a fancy dialog displaying str(exception)
If I test it it works fine however in the production enviornment it failes.
For testing I launch my program in Eclipse (PyDev), the production enviornment is a third party application written in Java, that has a Jython console build in. The application supports adding of custom menu entries, and putting jython scripts on these.
The main difference I see between testing and production enviornment is that in the production enviornment the swing threads are allready started (the third party application utilitizes swing). Does this cause my ThreadGroup setting to fail, or is there another reason why this is not working?
How can I get the Involved threads (exceptions ar thrown as a result of buttonActions) to check their defaultException handlers? If (as I am afraid) it should turn out that the third party installed its own handler (all exceptions are written to a log file) how can I make a new swing worker thread? (I don't want to catch the exceptions created by the host application after all)
Question recap:
1. How can I check which threads are started for the function func passed into the launcher function and see thier uncaught exception handler?
2. Can I enforce a seperate swing dispatcher for my gui part and the main applications gui part? (If I exitOnClos on a frame of my add in, the third party application closes)?
Update:
Considering the anwser from lbalazscs I am trying to use the sun.awt.exception.handler property, but it has no effect, the exceptions still end up in the log file (applications dfeault behaviour). Am I using it right? (p.s.: I am on Java 1.6)
If you have Java 5 or higher, you can also use Thread.setDefaultUncaughtExceptionHandler(), which is also described in a newer "Java Specialists' Newsletter":
http://www.javaspecialists.eu/archive/Issue089.html
And here is the newest Java 7 version:
http://www.javaspecialists.eu/archive/Issue196.html
Also see this:
Why bother with setting the "sun.awt.exception.handler" property?
EDIT: This is how I use Thread.setDefaultUncaughtExceptionHandler (in Java...):
public static void setupGlobalExceptionHandling() {
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
#Override
public void uncaughtException(Thread t, Throwable e) {
handleException(e);
}
});
}