【发布时间】:2018-01-13 19:19:47
【问题描述】:
我正在尝试使用多处理函数运行我的代码,但 mongo 不断返回
"MongoClient 在 fork 之前打开。创建 MongoClient 用 connect=False,或者fork后创建客户端。”
我真的不明白如何使我的代码适应这种情况。 基本上结构是:
db = MongoClient().database
db.authenticate('user', 'password', mechanism='SCRAM-SHA-1')
collectionW = db['words']
collectionT = db['sinMemo']
collectionL = db['sinLogic']
def findW(word):
rows = collectionw.find({"word": word})
ind = 0
for row in rows:
ind += 1
id = row["_id"]
if ind == 0:
a = ind
else:
a = id
return a
def trainAI(stri):
...
if findW(word) == 0:
_id = db['words'].insert(
{"_id": getNextSequence(db.counters, "nodeid"), "word": word})
story = _id
else:
story = findW(word)
...
def train(index):
# searching progress
progFile = "./train/progress{0}.txt".format(index)
trainFile = "./train/small_file_{0}".format(index)
if os.path.exists(progFile):
f = open(progFile, "r")
ind = f.read().strip()
if ind != "":
pprint(ind)
i = int(ind)
else:
pprint("No progress saved or progress lost!")
i = 0
f.close()
else:
i = 0
#get the number of line of the file
rangeC = rawbigcount(trainFile)
#fix unicode
non_bmp_map = dict.fromkeys(range(0x10000, sys.maxunicode + 1), 0xfffd)
files = io.open(trainFile, "r", encoding="utf8")
str1 = ""
str2 = ""
filex = open(progFile, "w")
with progressbar.ProgressBar(max_value=rangeC) as bar:
for line in files:
line = line.replace("\n", "")
if i % 2 == 0:
str1 = line.translate(non_bmp_map)
else:
str2 = line.translate(non_bmp_map)
bar.update(i)
trainAI(str1 + " " + str2)
filex.seek(0)
filex.truncate()
filex.write(str(i))
i += 1
#multiprocessing function
maxProcess = 3
def f(l, i):
l.acquire()
train(i + 1)
l.release()
if __name__ == '__main__':
lock = Lock()
for num in range(maxProcess):
pprint("start " + str(num))
Process(target=f, args=(lock, num)).start()
此代码用于在 4 个不同的进程中读取 4 个不同的文件,同时将数据插入数据库中。 我只复制了部分代码,让你了解它的结构。
我已尝试将 connect=False 添加到此代码中,但没有...
db = MongoClient(connect=False).database
db.authenticate('user', 'password', mechanism='SCRAM-SHA-1')
collectionW = db['words']
collectionT = db['sinMemo']
collectionL = db['sinLogic']
然后我尝试在 f 函数中移动它(就在 train() 之前,但我得到的是程序找不到 collectionW、collectionT 和 collectionL。
我不是python或mongodb的专家,所以我希望这不是一个愚蠢的问题。
代码在 Ubuntu 16.04.2 和 python 2.7.12 下运行
【问题讨论】:
-
这并不是一个新话题,因为数据库连接的“线程安全”的一般概念已经存在了很长时间。可能是为什么错误消息如此具有描述性和精确性。您被告知仅在fork 之后才建立连接,以便连接仅 存在于工作进程中。如果你想要某种类型的 IPC 那么你使用别的东西来做到这一点。但是在进程/线程之间复制数据库句柄是“正确的”,并且已经很长时间了。
标签: python mongodb python-2.7 pymongo python-multiprocessing