Julia interact with Python

I have a python dict a_dict:

using PyCall
thread = pyimport("_thread")
py"""
from time import sleep
from random import randint, random
a_dict = {"A": 0}
def keepUpdate():
    while True:
        sleep(random())
        a_dict["A"] = randint(1, 20)
"""
thread.start_new_thread(py"keepUpdate", ())

The dict is keep changing. In Julia, I need to keep monitor the a_dict, and whenever a_dict[" A"] == 3, something would happen, for example:

function keep_watching(x)
    while true
        if x["A"] == 3
            println("the dict get 3")
        end
    end
end
Threads.@spawn keep_watching(py"a_dict")

But in the codes, the monitor part while true is consume too much computer sources. Is there a better way to do it?

this sounds like a very bad way of doting anything.

what’s your actual problem / objective?

1 Like

I have some data being updated in python codes. I need to call a julia function whenever the data finish a updating. The updating interval is not fixed, and I need very low latence bettween the updating time (finished in python code) and function call (finished in julia code). Actucally the function is just a kind of callback function.

make that python function blocking? I mean if you call a python function from Julia, it won’t return until it finishes.

1 Like

In particular, I would generally encourage you to think in terms of calling Python functions and methods from Julia rather than running Python “scripts” in Julia (and somehow monitoring them asynchronously). Function calls are generally the best way to pass data and results from one part of a program to another, whether in the same language or between languages.

On a separate note, Python is not thread-safe so it’s problematic to try to interact with Python running on one thread from another Julia thread.

4 Likes