[英]How to exchange data back and forth between two separate processes in Python
[英]Exchange values between two processes?
我在樹莓派上運行了為python 2.7編寫的python腳本。 我想做的是帶步進電機前進,同時檢查前方是否有正方形。 為了避免這些干擾,我想將圖像處理移至其自己的過程,並在執行進一步步驟之前檢查是否找到了圖像。
這些是涉及的類。
SharedImageDetectionValue
:
class SharedImageDetectionValue(object):
stored_has_position_found = False
def get_has_position_found(self):
return self.stored_has_position_found
def set_has_position_found(self, new_value):
self.stored_has_position_found = new_value
return self.stored_has_position_found
ImageProcessor
:
class ImageProcessor:
def __init__(self):
# constructor code
def run(self, shared):
# do image processing till found a square
shared.set_has_position_found(True)
Stepper
:
class Stepper(Observable):
def __init__(self):
# constructor code
def run_until_stopped(self, shared):
# some motor code
while self.running:
has_found = shared.get_has_position_found()
print("[ StepperH ] Value has found: " + str(has_found))
if not has_found:
self.do_steps(0.0005)
ProcessManager:
class ProcessManager(BaseManager):
pass
我嘗試以此創建流程:
ProcessManager.register('SharedImageDetectionValue', SharedImageDetectionValue)
manager = ProcessManager()
manager.start()
shared = manager.SharedImageDetectionValue()
pool = Pool(1)
imgProcessor = ImageProcessor()
pool.apply_async(imgProcessor.run, args=(shared, ))
print("[ MAIN ] StepperH add to pool")
Stepper().run_until_stopped(shared)
出於測試目的,我直接在圖像處理器中將該值設置為true,但在步進器中則保持False。 我也嘗試將Stepper
也添加到池中,但似乎步進器隨后也無法運行。
我也嘗試通過兩個輔助函數調用流程,但效果相似:
def start_processing(passed_shared):
ImageProcessor().run(passed_shared)
def start_moving_to_target_platform(passed_shared):
StepperH().run_until_stopped(passed_shared)
我究竟做錯了什么?
當您只想共享一個值時,為什么要使用自定義管理器使事情變得復雜-而multiprocessing.Value
正是為此而存在。 另外,如果僅要使用它來運行單個進程,那么創建進程池是沒有意義的。
您可以將代碼簡化為:
import ctypes
import multiprocessing
class ImageProcessor(multiprocessing.Process):
def __init__(self, shared):
super(ImageProcessor, self).__init__()
self.shared = shared
def run(self):
# do image processing till found a square
self.shared.value = True
class Stepper(Observable):
def run_until_stopped(self, shared):
while self.running:
print("[ StepperH ] Value has found: {}".format(shared.value)
if not shared.value:
self.do_steps(0.0005)
# rest of your Stepper code
if __name__ == "__main__": # a multiprocessing guard
shared = multiprocessing.Value(ctypes.c_bool, False)
img_processor = ImageProcessor(shared)
img_processor.start()
Stepper().run_until_stopped(shared)
無需犧牲任何現有功能。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.