I have three python files: glob_var.py, read_cam.py, read_globVar.py. Their contents are as below: glob_var.py:
globVar = {}
def set(name, val):
globVar[name] = val
def get(name):
val = globVar.get(name, None)
return val
read_cam.py
import cv2
import glob_var
if __name__ == '__main__':
cam = cv2.VideoCapture(0)
key = 0
while key != 27:
ret, img = cam.read()
cv2.imshow('img', img)
key = cv2.waitKey(1) & 0xFF
glob_var.set('image', img)
read_globVar.py
import glob_var
import cv2
from time import sleep
if __name__ == '__main__':
key = 0
while key != 27:
img = glob_var.get('image')
if img is None:
print(f"no image in globVar")
sleep(1)
continue
print(f"read image with shape {img.shape}")
cv2.imshow('image', img)
key = cv2.waitKey(1) & 0xFF
From those three python flies, I think you guys know what I want to do. Yes, I want read_cam.py to read images from the camera and broadcast it to a global variable. Then read_globVar.py can get the image an show it. I run read_cam.py in one terminal and read_globVar.py in another one. But I did not make it work properly. Is what I am thinking possible? How can I manage it? Thanks a lot!
=====update1: Pub and Sub in python=====
I have used the ROS(Robot Operating System) system for a while. It provide the pub and sub funtion to exchange variables between different programs or so called node. So my question is that is there any package in python provide such function? Redis provide this, is it the fastest or best way?