この関数を定義しました
def writeonfiles(a,seed):
random.seed(seed)
f = open(a, "w+")
for i in range(0,10):
j = random.randint(0,10)
#print j
f.write(j)
f.close()
ここで、aはファイルのパスを含む文字列であり、seedは整数シードです。単純なプログラムを並列化して、各コアが指定した使用可能なパスの1つを取り、そのランダムジェネレーターをシードし、そのファイルに乱数を書き込むようにしたいので、たとえば、ベクトルを渡すと
vector = [Test/file1.txt, Test/file2.txt]
と種子
seeds = (123412, 989898),
それは最初に利用可能なコアに機能を与えます
writeonfiles(Test/file1.txt, 123412)
そして2番目のものに異なる引数を持つ同じ関数:
writeonfiles(Test/file2.txt, 989898)
Stackoverflowで同様の質問をたくさん調べましたが、解決策を機能させることはできません。私が試したのは:
def writeonfiles_unpack(args):
return writeonfiles(*args)
if __name__ == "__main__":
folder = ["Test/%d.csv" %i for i in range(0,4)]
seed = [234124, 663123, 12345 ,123833]
p = multiprocessing.Pool()
p.map(writeonfiles, (folder,seed))
TypeErrorが発生します:writeonfiles()は正確に2つの引数(1つ指定)を取ります。
私も試しました
if __name__ == "__main__":
folder = ["Test/%d.csv" %i for i in range(0,4)]
seed = [234124, 663123, 12345 ,123833]
p = multiprocessing.Process(target=writeonfiles, args= [folder,seed])
p.start()
しかし
、シードsuper(Random、self).seed(a)TypeError:unhashable type: 'list'にファイル "/usr/lib/python2.7/random.py"、行120が表示されます。
最後に、contextmanagerを試しました
@contextmanager
def poolcontext(*args, **kwargs):
pool = multiprocessing.Pool(*args, **kwargs)
yield pool
pool.terminate()
if __name__ == "__main__":
folder = ["Test/%d" %i for i in range(0,4)]
seed = [234124, 663123, 12345 ,123833]
a = zip(folder, seed)
with poolcontext(processes = 3) as pool:
results = pool.map(writeonfiles_unpack,a )
その結果、ファイル "/usr/lib/python2.7/multiprocessing/pool.py"、行572、get raiseself._valueになります。
TypeError: 'モジュール'オブジェクトは呼び出せません
Python 2.7には、starmap
Python3.3以降のpoolメソッドがありません。これを克服するには、ターゲット関数をラッパーで装飾します。ラッパーは、引数タプルを解凍し、ターゲット関数を呼び出します。
import os
from multiprocessing import Pool
import random
from functools import wraps
def unpack(func):
@wraps(func)
def wrapper(arg_tuple):
return func(*arg_tuple)
return wrapper
@unpack
def write_on_files(a, seed):
random.seed(seed)
print("%d opening file %s" % (os.getpid(), a)) # simulate
for _ in range(10):
j = random.randint(0, 10)
print("%d writing %d to file %s" % (os.getpid(), j, a)) # simulate
if __name__ == '__main__':
folder = ["Test/%d.csv" % i for i in range(0, 4)]
seed = [234124, 663123, 12345, 123833]
arguments = zip(folder, seed)
pool = Pool(4)
pool.map(write_on_files, iterable=arguments)
pool.close()
pool.join()
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加