Table of contents
- The context
- Minimal working examples
- Minimal working example 1
- Minimal working example 2
- The questions
The context
I’ve noticed that the output of some Python code is different in the built-in “Debug Console” than when it is run in a terminal. Let me show you some minimal working examples.
Minimal working examples
Minimal working example 1
The following code block contains a minimal working Python example that shows how to search a dictionary in a list of dictionaries. It was retrieved from this answer at Stack Overflow.
dicts = [
{"name": "Tom", "age": 10},
{"name": "Mark", "age": 5},
{"name": "Pam", "age": 7},
{"name": "Dick", "age": 12}
]
name_to_search = "Pam"
print(next(item for item in dicts if item["name"] == name_to_search))
The following is the result of running it in a terminal
$ python3 minimal-working-example-1.py
{'name': 'Pam', 'age': 7}
$ echo $?
0
The following is the result of running it in the “Debug Console”
>>> dicts = [
... {"name": "Tom", "age": 10},
... {"name": "Mark", "age": 5},
... {"name": "Pam", "age": 7},
... {"name": "Dick", "age": 12}
... ]
...
... name_to_search = "Pam"
...
... print(next(item for item in dicts if item["name"] == name_to_search))
Traceback (most recent call last):
File "aqt.debug_console", line 292, in onDebugRet
File "<string>", line 10, in <module>
File "<string>", line 10, in <genexpr>
NameError: name 'name_to_search' is not defined
Minimal working example 2
The following code block contains a minimal working Python example that shows how to search =a= in the string =abc=.
import re
def my_function():
print(re.search('a', 'abc'))
my_function()
The following is the result of running it in a terminal
$ python3 minimal-working-example-2.py
<re.Match object; span=(0, 1), match='a'>
$ echo $?
0
The following is the result of running it in the “Debug Console”
>>> import re
...
... def my_function():
... print(re.search('a', 'abc'))
...
... my_function()
Traceback (most recent call last):
File "aqt.debug_console", line 292, in onDebugRet
File "<string>", line 6, in <module>
File "<string>", line 4, in my_function
NameError: name 're' is not defined
The questions
- From the two aforementioned minimal working examples, I conclude that Anki’s “Debug Console” misbehave in some scenarios, so my question is: What are more consistent ways to execute arbitrary Python code in Anki?
- Is it possible to send a Python script that exists in a file so that it is run inside Anki? (something like this `$ python3 execute-in-anki.py my-script.py`. By doing this, we avoid using the “Debug Console”)