gpt4 book ai didi

python - Windows 机器上 IPython 控制台中的多处理 - 如果 __name_ 要求

转载 作者:可可西里 更新时间:2023-11-01 09:47:39 25 4
gpt4 key购买 nike

我在 Windows 机器上使用 IPython 和 Spyder IDE。当 IDE 启动时,会加载一组 py 文件来定义一些使我的工作更轻松的函数。一切都按预期进行。

现在我想升级其中一个函数以使用多处理,但在 Windows 上这需要 if __name__ == "__main__": 语句。所以我似乎无法直接调用该函数并从 IPython 控制台传递参数。

例如,其中一个 py 文件(我们称之为 test.py)可能类似于以下代码。

import multiprocessing as mp
import random
import string

# define a example function
def rand_string(length, output):
""" Generates a random string of numbers, lower- and uppercase chars. """
rand_str = ''.join(random.choice(
string.ascii_lowercase
+ string.ascii_uppercase
+ string.digits)
for i in range(length))
output.put(rand_str)


def myFunction():
# Define an output queue
output = mp.Queue()

# Setup a list of processes that we want to run
processes = [mp.Process(target=rand_string, args=(5, output)) for x in range(4)]

# Run processes
for p in processes:
p.start()

# Exit the completed processes
for p in processes:
p.join()

# Get process results from the output queue
results = [output.get() for p in processes]

print(results)

在我的 IPython 控制台中,我想使用这条线

myFunction()

触发所有的计算。但在 Windows 上最终会出现 BrokenPipe 错误。

当我放

if __name__ == "__main__":
myFunction()

在 py 文件的末尾运行完整的文件

runfile(test.py)

它有效。当然。但这使得向函数传递参数变得非常困难,因为我总是必须自己编辑 test.py 文件。

我的问题是:如何在不将多处理函数放入此 if __name__ == "__main__": 语句中的情况下运行它??

最佳答案

所以,我解决了这个具体问题。

  1. rand_string 的定义放在一个单独的文件中,称为test2.

  2. test2 作为模块导入到我的 test.py 脚本中

    将 test2 导入为 test2

  3. 修改以下行以访问test2模块

    processes = [mp.Process(target=test2.rand_string, args=(5, output)) for x in range(4)]
  4. 运行test.py

  5. 调用myFunction()

  6. 快乐:)

解决方案是基于这个multiprocessing tutorial这建议从另一个脚本导入目标函数。此解决方案绕过 if __name__ -wrapper 的安全 self 导入以访问目标函数。

关于python - Windows 机器上 IPython 控制台中的多处理 - 如果 __name_ 要求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29630217/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com