Python多处理过早关闭
我正试图将多处理集成到一个项目中,但我无法让它工作。 这就是我得到的:Python多处理过早关闭,python,windows,python-3.x,Python,Windows,Python 3.x,我正试图将多处理集成到一个项目中,但我无法让它工作。 这就是我得到的: import time import winsound from multiprocessing import Process winsound.MessageBeep() def pr1(): while 1: winsound.MessageBeep() time.sleep(0.5) if __name__ == '__main__': p = Process(targe
import time
import winsound
from multiprocessing import Process
winsound.MessageBeep()
def pr1():
while 1:
winsound.MessageBeep()
time.sleep(0.5)
if __name__ == '__main__':
p = Process(target=pr1, args=())
p.start()
p.join()
while 1:
print('hey')
但如果我运行它,我只听到一声嘟嘟声,我希望它重复。我该怎么做
b计划,
我现在得到了这个,我只得到了正确的答案:
import time
import winsound
from multiprocessing import Process
def pr1():
while 1:
winsound.MessageBeep()
print('its working')
time.sleep(0.5)
if __name__ == '__main__':
print('correct')
p = Process(target=pr1, args=())
p.start()
p.join()
while 1:
print('hey')
因此,创建流程存在一些问题。
有什么想法吗?缩进决赛
while 1:
print('hey')
使其成为if
块的一部分
在Windows下启动子进程时,首先执行模块内容,然后运行指定为target
的可调用进程。因为模块从未完成执行,所以不会发生这种情况
第二个片段作为一个整体变成:
import time
import winsound
from multiprocessing import Process
def pr1():
while 1:
winsound.MessageBeep()
print('its working')
time.sleep(0.5)
if __name__ == '__main__':
print('correct')
p = Process(target=pr1, args=())
p.start()
p.join()
while 1:
print('hey')
要显示“its working”消息,您需要刷新缓冲区,因为通常在进程中,输出通常是缓冲的
import time
import winsound
from multiprocessing import Process
import sys
def pr1():
while 1:
winsound.MessageBeep()
print('its working')
time.sleep(0.5)
sys.stdout.flush()
if __name__ == '__main__':
print('correct')
p = Process(target=pr1, args=())
p.start()
p.join()
如果
\uuuu name\uuuu=='\uuuuu main\uuuuu':
有效?我不在Windows上,因此无法检查它,但它看起来应该有效。如果在调用winsound.MessageBeep()
之前或之后添加打印语句,会发生什么情况?你能看到它在打印什么东西吗?这很奇怪,我甚至不能让Python文档页面上的print hello
示例正常工作。我从未使用过多处理,但我使用过线程。我不确定这是否能满足你的需要,但效果相当不错。我把代码改成了这个,现在屏幕上唯一的东西是正确的。导入时间从多处理导入进程def pr1()导入winsound:while 1:winsound.MessageBeep()打印(“其工作”)时间。睡眠(0.5)如果名称='main':打印('correct')p=Process(target=pr1,args=())p.start()p.join()而1:打印(‘嘿’)更新问题中的代码。没有人能在评论中读Python。我不知道你的意思。如果缩进while语句,则会发生北移还是我必须移动它?@CvR\u XX如果缩进,则仅当If
-语句为true(仅在父进程中发生)时才会执行。我用你的第二段代码试过了,它对我很有用。我可能有点困,但我还是不明白。请你把第二段代码与你的编辑一起发布。奇怪的是,即使有了这段代码,我也只看到“正确”,而没有看到“嘿”和“正在工作”的好工作窗口,由于有数百个python进程,它突然开始工作,导致大量噪音和pc速度缓慢