【问题标题】:Python Multiprocessing runs entire Program instead of called functionPython Multiprocessing 运行整个程序而不是调用函数
【发布时间】:2020-06-15 13:11:06
【问题描述】:
from multiprocessing import Process
import time

print('test')

def plint():
    print('here')

def parallel():
    if __name__ == "__main__":
        p1 = Process(target = plint)
        p1.start()

while True:
    parallel()
    time.sleep(2)

程序一直只输出'test',没有进入'plint'函数并打印'here'。有人可以帮忙吗?

编辑:当我在没有循环的情况下运行相同的代码时,它会输出两次“测试”,然后打印一次“这里”。使用循环它甚至不会到达“这里”。

【问题讨论】:

标签: python multithreading


【解决方案1】:

尤其是在 Windows 上,多处理脚本的主要入口点 must be guarded by if __name == "__main__":(请参阅“安全导入”部分)。

from multiprocessing import Process
import time
import os


def plint():
    print("here", os.getpid())


def parallel():
    p1 = Process(target=plint)
    p1.start()


def main():
    print("test")
    while True:
        parallel()
        time.sleep(2)


if __name__ == "__main__":
    main()

【讨论】:

  • 现在可以了!问题是它运行主函数之外的所有内容,因此即使不应该打印“测试”。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-07-03
  • 2022-01-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多