[英]How can we run 2 python scripts that share a common variable in parallel?
首先让我解释一下场景。
我的项目是使用 Django 构建的。
我有前端,我们可以在其中上传一个人的图像。 该图像将存储在我们本地计算机的(媒体文件夹)中。
例如:如果图像名称是jon.jpeg
,那么它将被存储为
media
-jon
--jon.jpeg
如果上传了另一张图片,比如bob.jpg
,那么结构将如下所示:
media
-jon
--jon.jpeg
-bob
--bob.jpg
现在我有一个 Python 脚本(比如check.py
),我们在其中运行一个无限循环,并且每 5 秒检查一次媒体文件夹中的文件夹数量。 此外,我们在check.py
中维护一个全局变量,用于跟踪 initial_count。
现在我有另一个 Python 文件正在运行(即camera.py
),它有两个功能,即load_encodings
并在名为Face_Recog
的 class 中recognize
。
load_encodings
会将媒体文件夹中的图像转换为特征编码,并将这些编码存储在camera.py
文件中的全局列表 ( known_faces
) 中。
recognize
将首先从一个相机帧中提取图像并对其进行编码,然后将其与known_faces
中的编码进行比较。
现在,每当media
中的文件夹数量发生变化时(如果我们从前端上传图像),那么check.py
中的initial_count
就会发生变化。 我们给出了一个条件,如果initial_count
值发生变化,它将调用camera.py
文件的encoding
function。
check.py
from camera import Face_Recog,object
initial_count = 0
while True:
count = 0
for path in os.listdir(path/to/media):
count += 1
global initial_count
if count != initial_count:
Face_Recog.load_encodings(object)
initial_count = count
sleep(5)
camera.py
known_faces = []
class Face_Recog(object):
def load_encodings(self):
temp = []
#some code that will change the temp value , i.e it will load the image from media and then encode it and store the encoding in temp
global known_faces
known_faces = temp
def recognize(self):
while(True):
#code that uses known_faces and recognizes
object = Face_Recog()
object.load_encodings()
object.recognize()
现在我在 2 个不同的 shell 中运行这两个文件。
最初,媒体文件夹仅包含jon
,因此known_faces
将仅包含jon
的编码。
known_faces = ['jon']
并且recognize
function 不会识别bob
,它只会识别jon
。
(这是有效的。)
现在,当我上传bob
的图像时, check.py
中的initial_count
值会发生变化,它会调用load_encodings
的 load_encodings camera.py
(它正在调用它;我已经使用打印语句进行了检查)。
现在这个 function 将再次编码存在的图像,即jon
和bob
,并更新全局变量,即known_faces
。
(It is updating, but only in the shell in which check.py
is running, not in the shell running camera.py
. Ie it is not reflecting the changes in the camera.py
file's known_faces
variable, which is running in a different shell实例)。
因此,即使它正在更改known_faces
变量, recognize
function 也无法识别bob
,即它正在使用的变量 ( known_faces
) 不会自动更新。
我想做一些事情,比如每当有人从前端上传任何图像时,它的编码应该在文件( camera.py
)中更新而不停止相机,即recognize
function 不应停止其执行。
PS。 注意:这两个文件,即camera.py
和check.py
一直在 2 个不同的 shell 中运行。
请告诉我是否有可能,或者是否有任何其他方法可以实现这一目标。
最简单的解决方案可能是让check.py
监视文件并在必要时重新启动其他进程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.