【发布时间】:2015-12-14 11:19:49
【问题描述】:
我需要运行一个 shell 脚本,它从服务器获取文件并根据传递给它的参数写入磁盘。我需要为大约 20 多个不同的参数运行此脚本,因此需要为每个参数并行运行它。
我尝试在 python 中使用Pool、apply_async 和join 来完成此操作。但这似乎不起作用。下面是代码:
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