Edit and run python code inside Logseq itself

UPDATE: Today (i.e. after months) the system sent me this message concerning this post: “Your post was flagged as inappropriate”. I have no idea what this is about or what to do about it. If anyone has a clue, please contact me.


  • The theoretical background and discussion is here.
  • This is a natural continuation of the work done in Edit and run javascript code inside Logseq itself
    • The implementation there supports multiple languages, so it is not repeated here.
    • This is opened as a separate thread, in order to hold the python-specific material and discussion.

This is far from an original idea, consider reading Logseq like Jupyter Notebook et similia
Among other things, there @aarimond suggested the use of Pyodide, which is adopted here.

Current Features:

  • It loads Pyodide the first time that is needed per Logseq’s restart.
    • The predefined address is at jsdelivr.com , which needs an internet connection.
      • You may provide a different address by setting Python.pyodideUri
  • It doesn’t load other packages.
    • Instructions can be found online (e.g. here).
  • All the integrated parts are provided from third parties.
    • Their quality is not perfect.
    • Use at own risk.
      • Expect failures in various cases.
      • Thoroughly test all code before using it in production.
  • More info and abilities found in Edit and run javascript code inside Logseq itself, so not repeated here.

Check for the following messages during first run:
image

image

Simple example

image

Graphics example using matplotlib

Example of mixing and running javascript and python in the same page

Use the following markdown in a page:

- Code
	- {{runpage}}
	-
	  ```javascript
	  logseq.can_run = "java?";
	  ```
	-
	  ```python
	  import js
	  
	  def pyfun(str):
	    return js.logseq.can_run[:-1] + str + " & py"
	  
	  js.logseq.kits.pyfun = pyfun
	  ```
	-
	  ```javascript
	  logseq.can_run = logseq.kits.pyfun("script");
	  ```
	-
	  ```python
	  js.logseq.can_run += "thon"
	  ```
	-
	  ```javascript
	  alert("Logseq can edit & run: clojure & " + logseq.can_run + " & r-language");
	  ```

Should look like this:

Press the button for javascript and python to collaborate back and forth, joining forces to produce a fact.

Inspired by mentaloid’s work I have created a graph and video that demonstrate how to execute code within logseq. It includes many python examples such as Jupyter like behaviour, accessing pages and blocks and sending code execution results to logseq pages, the console, javascript alerts and logseq messages.

Video url: https://youtu.be/u1hi7HjG66A
Github repo where you can download the graph: GitHub - adxsoft/logseq-code-execution-demo-graph: A logseq graph that demonstrates how to use python and/or javascript code within a logseq graph giving Jupyter like behaviours - includes using logseq API calls to get pages and blocks and run queries 1

3 Likes