有没有办法检查模块是否正在被 Windows 中的多处理标准模块加载? [英] Is there a way to check if a module is being loaded by multiprocessing standard module in Windows?

查看:51
本文介绍了有没有办法检查模块是否正在被 Windows 中的多处理标准模块加载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我相信在 Windows 上,因为没有 forkmultiprocessing 模块会在新的 Python 进程中重新加载模块.

I believe on Windows, because there is no fork, the multiprocessing module reloads modules in new Python's processes.

你需要在你的主脚本中有这个代码,否则会发生非常讨厌的崩溃

You are required to have this code in your main script, otherwise very nasty crashes occur

if __name__ == '__main__':
    from multiprocessing import freeze_support
    freeze_support()

我有一堆模块,它们在模块级别有调试打印语句.因此,每当加载模块时都会调用打印语句.

I have a bunch of modules which have debug print statements in them at the module level. Therefore, the print statements get called whenever a module is being loaded.

每当我并行运行某些东西时,所有这些打印语句都会被执行.

Whenever I run something in parallel all of these print statements are executed.

我的问题是,是否有一种方法可以查看 multiprocessing 模块是否正在导入一个模块,如果是这样,则使这些打印语句静音?

My question is if there is a way to see if a module is being imported by the multiprocessing module, and if so silence those print statements?

我基本上是在看是否有类似的东西:

I'm basically looking if there is something like:

 import multiprocessing
 if not multiprocessing.in_parallel_process:
     print('Loaded module: ' + __name___)

到目前为止我一直无法找到它.这可能吗?

I've been unable to find it so far. Is this possible?

推荐答案

对于 Python 3.8 和更新版本,请使用 multiprocessing.parent_process() 返回 None 仅对于主进程和早期版本检查是否 name 属性的值等于 MainProcess.

For Python 3.8 and newer use multiprocessing.parent_process() which returns None only for the main process and for earlier versions check if name attribute's value equals MainProcess.

from multiprocessing import Process, current_process

if current_process().name == 'MainProcess':
    print('Hello from the main process')
else:
    print('Hello from child process')

def f(name):
    print('hello', name)

if __name__ == '__main__':
    p = Process(target=f, args=('bob',))
    p.start()
    p.join()

输出:

Hello from the main process
Hello from child process
hello bob

这篇关于有没有办法检查模块是否正在被 Windows 中的多处理标准模块加载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆