【问题标题】:Python: Working with Pool, apply_async and joinPython:使用 Pool、apply_async 和 join
【发布时间】:2015-12-14 11:19:49
【问题描述】:

我需要运行一个 shell 脚本,它从服务器获取文件并根据传递给它的参数写入磁盘。我需要为大约 20 多个不同的参数运行此脚本,因此需要为每个参数并行运行它。

我尝试在 python 中使用Poolapply_asyncjoin 来完成此操作。但这似乎不起作用。下面是代码:

  import yaml
  from subprocess import call
  from multiprocessing import Pool

  feeder_server_conf = "/etc/feeder-servers.conf"
  with open("feed_conf.yaml", "r") as stream:
        feeds = yaml.load_all(stream)
        pool = Pool()
        for feed in feeds:
            for key, value in feed.items():
                keep_count_present = False
                name = value['name']
                age = value['age']
                if 'keep-count' in value:
                    keep_count = value['keep-count']
                    keep_count_present = True

                print "Pulling feed..."

                if keep_count_present:
                    command = "/usr/bin/pull-feed --name " + name + " --config " + feeder_server_conf + " --age " + str(age) + " --keep-count " + str(keep_count)
                else:
                    command = "/usr/bin/pull-feed --name " + name + " --config " + feeder_server_conf + " --age " + str(age)
                pool.apply_async(call, command.split())

        print "Waiting for pull-feeds to finish..."
        pool.close()
        pool.join()

该代码仅打印以下输出并退出而不提取任何文件。不知道我在这里缺少什么。任何帮助表示赞赏。谢谢!

Pulling feeds...
Pulling feed...
Pulling feed...
Pulling feed...
Pulling feed...
Pulling feed...
Pulling feed...
Pulling feed...
Pulling feed...
Pulling feed...
Pulling feed...
Pulling feed...
Pulling feed...
Pulling feed...
Pulling feed...
Pulling feed...
Pulling feed...
Pulling feed...
Pulling feed...
Pulling feed...
Pulling feed...
Pulling feed...
Waiting for pull-feeds to finish...

我尝试执行的脚本在单独运行时运行良好(因此不是罪魁祸首)。我希望代码等到所有文件都被拉出。不知道我在这里缺少什么。我没有以正确的方式使用构造吗?任何帮助表示赞赏。谢谢!

【问题讨论】:

  • call替换为check_call,然后在发生错误时会得到一个异常,而不是静默失败。
  • 没有帮助。仍然得到相同的输出,没有别的。
  • 快速建议:在finally 部分中使用pool.close()try 中创建您的池(或者更好的是,如果可能,使用with 语句)以避免留下cess@ 987654332@ 个正在运行的进程,以防中间代码抛出异常。
  • @musically_ut:会做出改变。谢谢!

标签: python python-2.7 asynchronous subprocess python-multiprocessing


【解决方案1】:

这里的问题很简单,如documentation of subprocess.call 中所述,call 的第一个参数是 list,但 apply_async 函数将第二个参数中的列表应用为 @987654324 @会,这意味着你的电话最终会看起来像这样call('/usr/bin/pull-feed', '--name', ...),这不是你使用call的方式。您需要做的就是将pool.apply_async(call, command.split()) 替换为pool.apply_async(call, [command.split()]),将您的命令作为列表传递给call 的第一个参数,apply_async 使用的最终命令将如下所示call(['/usr/bin/pull-feed', '--name'])

【讨论】:

  • 这修复了它。谢谢!
猜你喜欢
  • 2012-03-24
  • 2018-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-05
相关资源
最近更新 更多