尝试生成多个进程(图像检测和打印到终端)时出现运行时错误



我遵循本指南,试图看看是否可以运行一个简单的多处理脚本。在其他问题中已经讨论过,我需要使用多处理来实现我想要实现的目标。

为了遵循初学者指南,我编写了两个函数。

import pyautogui as py
import multiprocessing
def print_i():
for i in range(0, 21):
print(i)
sleep(0.1)
image = r'C:Usersimage.jpg'
def closeWindow():
while True:
found = py.locateCenterOnScreen(image)
if found != None:
py.click(1797, 134)

print_i打印出数字0-20,closeWindow检查特定窗口是否打开,如果找到,则单击关闭,两者都单独工作。

在以下指南中,我导入了multiprocessing并完成了以下操作:

p1 = multiprocessing.Process(target= print_i)
p2 = multiprocessing.Process(target= closeWindow)
p1.start()
p2.start()
p1.join()
p2.join()

然而,我立即得到以下错误两次:

RuntimeError:
An attempt has been made to start a new process before the
current process has finished its bootstrapping phase.
This probably means that you are not using fork to start your
child processes and you have forgotten to use the proper idiom
in the main module:
if __name__ == '__main__':
freeze_support()
...
The "freeze_support()" line can be omitted if the program
is not going to be frozen to produce an executable.

这个堆栈解释说,多处理模块应该处理这些情况,并在目标运行之前就检测到您正在尝试启动新的进程。

在阅读中提到的不使用fork启动子进程的错误时,我认为我没有子进程,在多处理时,第一个进程之后的任何事情都算作子进程吗?如果是,如何在同时运行图像检测的同时,用一个进程输出数字0-20?

有很多方法可以连续安排或运行任务。以下是几个例子:

使用线程:

from threading import Thread
from time import sleep
def run_close_window_task():
while True:
print("Hello, close window task is running!")
sleep(2)
t = Thread(name='backgroundtask', target=run_close_window_task)
t.start()
print("Now we are doing other stuff, while the other task is running...")

注意:您必须通过Windows中的任务管理器终止Python进程才能停止它。

结果:

Hello, close window task is running!
Now we are doing other stuff, while the other task is running...
Hello, close window task is running!
Hello, close window task is running!
Hello, close window task is running!
...

使用异步:

from asyncio import sleep, run, create_task, gather
async def run_close_window_task():
while True:
print("Hello, close window task is running!")
await sleep(2)
async def print_i():
while True:
for i in range(0, 21):
print(f"Printing i: {str(i)}")
await sleep(0.2)
async def main():
tasks = [create_task(run_close_window_task()), create_task(print_i())]
await gather(*tasks, return_exceptions=False)
if __name__ == "__main__":
run(main())

结果:

Hello, close window task is running!
Printing i: 0
Printing i: 1
Printing i: 2
Printing i: 3
Printing i: 4
Printing i: 5
Printing i: 6
Printing i: 7
Printing i: 8
Printing i: 9
Hello, close window task is running!
Printing i: 10
Printing i: 11
Printing i: 12
Printing i: 13
Printing i: 14
Printing i: 15
Printing i: 16
Printing i: 17
Printing i: 18
Printing i: 19
...

相关内容

  • 没有找到相关文章

最新更新