2

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?

ekhumoro
  • 115,249
  • 20
  • 229
  • 336
kjo
  • 33,683
  • 52
  • 148
  • 265
  • Aren't you supposed to use the anki plugins *from* within anki? – musicamante Sep 12 '21 at 21:58
  • @musicamante: I'm not working on/with an anki plugin. I want to develop a cron (i.e. unsupervised/automatically running/non-interactive) script that accesses and possibly modifies my collection.anki2 database. – kjo Sep 13 '21 at 12:28
  • @eyllanesc: Apologies for rolling back your edit. The Python package this question is about consists primarily of a PyQt app, and I think the problem I am having with this has to do with this fact. – kjo Sep 13 '21 at 12:32
  • 1
    @kjo Try calling `app.processEvents()` before the other statements. – ekhumoro Sep 13 '21 at 13:03
  • @ekhumoro: Thank you very much! When I added `app.processEvents()` before the `print` statement, I still got output `None`, but adding `while aqt.mw.col is None: app.processEvents()` did the trick! I would be happy to accept this as the answer if you care to post it. – kjo Sep 13 '21 at 16:33
  • @kjo Glad you got it working. I have added an answer based on the comments. – ekhumoro Sep 13 '21 at 16:50

1 Answers1

1

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()
ekhumoro
  • 115,249
  • 20
  • 229
  • 336