【问题标题】:How to use a variable as a name for Another Function in Python [duplicate]如何在Python中使用变量作为另一个函数的名称[重复]
【发布时间】:2019-11-17 17:26:37
【问题描述】:

你好 stackoverflow 用户,

我的问题很直截了当:

如何在另一个命令的名称中使用变量?

我的脚本大致如下:

    for i in range(1, face_recognition_core_count+1):
    face_finder+i = multiprocessing.Process(target=find_faces, args=(total_frame_count, i))
    face_finder+i.start()
    face_finder+i.join()

【问题讨论】:

  • 不要。只需将进程添加到列表中,然后执行processes[i](或您对列表的任何名称)来检索它们。
  • 你能举例说明你的意思吗?

标签: python for-loop variables pip names


【解决方案1】:

使用字典。

face_finder_dict = {}
for i in range(1, face_recognition_core_count + 1):
    face_finder_dict[f"face_finder{i}"] = multiprocessing.Process(target=find_faces, args=(total_frame_count, i))
    face_finder_dict[f"face_finder{i}"].start()
    face_finder_dict[f"face_finder{i}"].join()

【讨论】:

  • @marcr 我编辑了代码以使用字符串名称。我以为您已经在原始帖子的示例代码中定义了 face_finder。
  • 嗨,这似乎也不起作用,因为启动的进程具有相同的名称。所以它只会创建一个名为 face_finder_dict 的进程,其他进程名称相同,无法创建。
  • 第一个过程是 face_finder_dict[f"face_finder0"] 的值,第二个过程是 face_finder_dict[f"face_finder1"] 的值,以此类推。为什么他们有相同的名字?
  • 我认为 python 忽略了 .start 和 .join 上的 [...]。我不知道如何绕过这个。
  • 啊,我发现了问题。我首先需要定义所有的多处理函数,然后才启动它们。
猜你喜欢
  • 2018-02-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-23
  • 2015-07-11
  • 2011-07-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多