gpt4 book ai didi

python - 为什么这段代码不能在并行 python 中工作

转载 作者:行者123 更新时间:2023-11-30 23:43:21 25 4
gpt4 key购买 nike

我尝试像这样使用 pp(Parallel Python):

import glob
import subprocess
import pp


def run(cmd):
print cmd
subprocess.call(cmd, shell=True)

job_server = pp.Server()
job_server.set_ncpus(8)
jobs = []
for a_file in glob.glob("./*"):
cmd = "ls"
jobs.append(job_server.submit(run, (cmd,)))
for j in jobs:
j()

但是遇到这样的错误,subprocess.call不是全局名称。

An error has occured during the function execution
Traceback (most recent call last):
File "/Library/Python/2.7/site-packages/pp-1.6.1-py2.7.egg/ppworker.py", line 90, in run
__result = __f(*__args)
File "<string>", line 3, in run
NameError: global name 'subprocess' is not defined

我已经导入了子流程,为什么这里不能使用?

根据abarnert的建议,我将代码更改为:

import glob
import pp
def run(cmd):
print cmd
subprocess.call(cmd, shell=True)
job_server = pp.Server()
job_server.set_ncpus(8)
jobs = []
for a_file in glob.glob("./*"):
cmd = "ls"
jobs.append(job_server.submit(run, (cmd,),modules=("subprocess",)))
for j in jobs:
j()

但它仍然不起作用,它提示如下:

Traceback (most recent call last):
File "/usr/lib/python2.6/threading.py", line 532, in __bootstrap_inner
self.run()
File "/usr/lib/python2.6/threading.py", line 484, in run
self.__target(*self.__args, **self.__kwargs)
File "/usr/local/lib/python2.6/dist-packages/pp-1.6.1-py2.6.egg/pp.py", line 721, in _run_local
job.finalize(sresult)
UnboundLocalError: local variable 'sresult' referenced before assignment

最佳答案

文档很好地解释了这一点,每个示例都向您展示了如何处理它。

提交方法的参数之一是“模块 - 带有要导入的模块名称的元组”。您希望在提交的作业中使用的任何模块都必须在此处列出。

所以,你可以这样做:

jobs.append(job_server.submit(run, (cmd,), (), ('subprocess',)))

或者这个:

jobs.append(job_server.submit(run, (cmd,), modules=('subprocess',)))

关于python - 为什么这段代码不能在并行 python 中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10841341/

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