Skip to content

Instantly share code, notes, and snippets.

@vjcitn
Last active September 25, 2025 01:55
Show Gist options
  • Select an option

  • Save vjcitn/634e722fe2eea78449bbe3dbd2a39d13 to your computer and use it in GitHub Desktop.

Select an option

Save vjcitn/634e722fe2eea78449bbe3dbd2a39d13 to your computer and use it in GitHub Desktop.
silly approach to starting napari from R
# based on https://alisterburt.com/napari-workshops/notebooks/viewer_intro.html
library(reticulate)
py_require("napari[all]")
py_require("scikit-image")
nap = import("napari")
v = nap$Viewer()
si = import("skimage")
#id = si$data$cells3d()
if (!file.exists("nuclei.tif")) {
system("wget --no-check-certificate https://raw.githubusercontent.com/alisterburt/napari-workshops/main/napari-workshops/notebooks/data/nuclei.tif")
}
if (!file.exists("cell_membranes.tif")) {
system("wget --no-check-certificate https://raw.githubusercontent.com/alisterburt/napari-workshops/main/napari-workshops/notebooks/data/cell_membranes.tif")
}
nuc = si$io$imread("nuclei.tif")
v$add_image(nuc)
mem = si$io$imread("cell_membranes.tif")
v$add_image(mem)
nap$run()
@vjcitn
Copy link
Author

vjcitn commented Sep 25, 2025

can this help avoid blocking?

2. Using coro (async/await) with reticulate:
Python function.
Same as above. R code with coro.
The coro package provides async and await keywords in R, making asynchronous code more sequential-looking.
Code

  library(reticulate)
  library(coro)
  library(future)

  # Ensure Python environment and import module as before
  py_run_string("import sys")
  py_run_string("sys.path.append('.')")
  my_python_module <- import("my_python_module")

  # Define an async R function
  my_async_r_function <- async(function() {
    result <- await(future({
      my_python_module$long_running_task(5)
    }))
    print(paste("Python task result (async/await):", result))
  })

  # Run the async function
  my_async_r_function()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment