2010-11-19 4 views
1

基本的には、クライアントがオペレーションデータベースとecommsサイトデータベース間でバッチジョブのインポートとエクスポートを処理するPythonスクリプトを選択しています。これはうまく動作します。これらのスクリプトはstdoutに書き込んでバッチスクリプトの状態をユーザーに通知します。Django Subprocessバッチスクリプトからのstdoutのライブ/バッファなしのレポート

私は、Djangoのビューを経由して実行されるように、これらのスクリプトのためのフレームワークを作成し、ユーザーにこれらのバッチ処理の進行状況を表示するウェブページにSTDOUTを投稿しようとしています。

- バッチスクリプトをサブプロセスとして呼び出し、stdoutとstderrをファイルに保存します。 - 標準出力ファイルの内容が書き込まれているラインで2秒ごとに、表示ラインをリロードします表示ページへのリダイレクトを返します。

ただし、バッチスクリプトの実行が完了するかエラーが発生するまで、stdout/stderrファイルは実際に書き込まれていないという問題があります。

私は物事の数を試してみたが、どれも動作するようには思えません。相続人は、現在のビューコード

def long_running(app, filename): 
    """where app is ['command', 'arg1', 'arg2'] and filename is the file used for output""" 
    # where to write the result (something like /tmp/some-unique-id) 
    fullname = temppath+filename 
    f = file(fullname, "a+") 
    # launch the script which outputs something slowly 
    subprocess.Popen(app, stdout=f, stderr=f)# .communicate() 
    # once the script is done, close the output 
    f.close() 

def attributeexport(request): 
    filename = "%d_attribute" %(int(time.time())) #set the filename to be the current time stamp plus an identifier 
    app = ['python','/home/windsor/django/applications/attribute_exports.py'] 
    #break thread for processing. 
    threading.Thread(target=long_running, args=(app,filename)).start() 
    return HttpResponseRedirect('/scripts/dynamic/'+filename+'/') 
    pass 

def dynamic(request, viewfile): 
    fileobj = open(temppath+viewfile, 'r') 
    results = [] 
    for line in fileobj: 
     results.append(line) 
     if '~END' in line: 
      #if the process has completed 
      return render_to_response('scripts/static.html', {'displaylist':results, 'filename':viewfile}) 
    return render_to_response('scripts/dynamic.html', {'displaylist':results, 'filename':viewfile}) 
pass 
+0

あなたの問題は、出力バッファです。これはあなたを助けるかもしれない、またはあなたが直接出力を読んでいないではないかもしれないので:http://stackoverflow.com/questions/803265/getting-realtime-output-using-subprocess – eternicode

+0

私は、処理を検討する必要がありかもしれないと思います更新されたログファイルを保存するためにキーポイントを設定し、元のスクリプトに引数としてファイル名を渡す...私は変更する必要がありますこれらのスクリプトがたくさんあるので、これを避けることを望んでいた。 – BenDog

答えて

1

次を使用する場合には役立ちます:

['python','-u','path/to/python/script.py'] 
+0

autoreloaderが必要な場合は、autoreloaderがPythonレベルのCLI引数をサブプロセスに渡さないため、 'PYTHONUNBUFFERED'環境変数を使用する必要があります。 – Joe

関連する問題