pythonpyqtevent-handlinganki

How to run Anki-Qt script without requiring a breakpoint?


If I run the toy script below as shown:

import sys
sys.path.append('/usr/share/anki')
import aqt

app = aqt._run(argv=['/usr/bin/anki', '--profile=test'], exec=False)
# breakpoint()
print(repr(aqt.mw.col))
aqt.mw.cleanupAndExit()

...I get the following output, which is not right:

$ python3 /tmp/ankiq.py
None

If I uncomment the commented statement, however, and re-run the modified script, I get the correct output (eventually):

$ python3 /tmp/ankiq.py
> /tmp/ankiq.py(8)<module>()
-> print(repr(aqt.mw.col))
(Pdb) c
<anki.collection._Collection object at 0x7f32ec1417b8>

I would like to avoid the need for the breakpoint() statement (and for having to hit c whenever I want to run such code).

My guess is that, when the breakpoint() statement is commented out, the print statement happens before aqt.mw has been fully initialized.

(I tried replacing the breakpoint() statement with time.sleep(1), but when I run the script with this modification, it hangs before ever printing any output.)

Q: How can I modify the toy script above so that, by the time the print statement executes, aqt.mw.col has its correct value?


Solution

  • It seems that calling aqt._run(*args, exec=False) returns a QApplication object - but without starting its event-loop. To manually process pending events, you could therefore try calling app.processEvents().


    From the comments, it appears the exact solution is as follows:

    while aqt.mw.col is None: 
        app.processEvents()