stata doファイルpyexample3.doがあります。このファイルは回帰を実行するための回帰子としてその引数を使います。回帰からのF-統計量はテキストファイルに保存されます。コードは以下の通りである:並列実行Stataはマルチプロセスとサブプロセスを使ってPythonでファイルを処理します
clear all
set more off
local y `1'
display `"first parameter: `y'"'
sysuse auto
regress price `y'
local f=e(F)
display "`f'"
file open myhandle using test_result.txt, write append
file write myhandle "`f'" _n
file close myhandle
exit, STATA clear
は、今私はPythonで並列にファイルと1つのテキストファイル内のすべてのF-の統計情報を書くのですSTATAを実行しようとしています。私のCPUは4つのコアを持っています。
import multiprocessing
import subprocess
def work(staname):
dofile = "pyexample3.do"
cmd = ["StataMP-64.exe","/e", "do", dofile,staname]
return subprocess.call(cmd, shell=False)
if __name__ == '__main__':
my_list =[ "mpg","rep78","headroom","trunk","weight","length","turn","displacement","gear_ratio" ]
my_list.sort()
print my_list
# Get the number of processors available
num_processes = multiprocessing.cpu_count()
threads = []
len_stas = len(my_list)
print "+++ Number of stations to process: %s" % (len_stas)
# run until all the threads are done, and there is no data left
for list_item in my_list:
# if we aren't using all the processors AND there is still data left to
# compute, then spawn another thread
if(len(threads) < num_processes):
p = multiprocessing.Process(target=work,args=[list_item])
p.start()
print p, p.is_alive()
threads.append(p)
else:
for thread in threads:
if not thread.is_alive():
threads.remove(thread)
doファイルはmy_listに9つの文字列があるため9回実行されるはずですが、4回だけ実行されました。どこが間違っていたのですか?あなたのfor list_item in my_list
ループでは
を今すぐファイルを実行すると、7回実行されるが、それでも2回が欠落しています。 0.5秒を変更すると数字も変わります。それはテキストファイルへの同時書き込みによって引き起こされますか? – user20726
それは可能性があります。同じファイルへの書き込みはスレッドセーフではないので、同時に異なるプロセスからファイルに書き込むと、予期しない結果が生じる可能性があるので、 'RLock'を使ってプロセスが1つだけであることを確認することができます同時にファイルを処理します。 – Shane