0

ここで定義されている非常に単純な python スクリプトがあります

import multiprocessing
from multiprocessing import Pool

print "CPUs: " + str(multiprocessing.cpu_count())
convertPool = Pool(multiprocessing.cpu_count())

Linux では、これは私の予想どおりに動作しているように見えます。プログラムが開始され、コア数が出力されてから終了します。ただし、Windows では、このプログラムは引き続き新しい python コマンドを呼び出し、「CPU: 4」(私は 4 つのコアを持っています) を出力し、実行を停止することはなく、最終的にはボックスを強制終了します。誰かがここで何が起こっているのか説明してもらえますか?

ありがとう

編集:私は今、期待どおりに動作しない次のプログラムを持っています

import sys
import os
import subprocess
from subprocess import Popen, PIPE
from threading import Thread
import multiprocessing
from multiprocessing import Pool, freeze_support

try:
    from Queue import Queue, Empty
except ImportError:
    from queue import Queue, Empty  # python 3.x

ON_POSIX = "posix" in sys.builtin_module_names

def myPrint(line, logWriter):
    if logWriter is None:
        # This will print without a newline, cause the process
        # has its own newlines
        sys.stdout.write(line)
    else:
        logWriter.write(line.strip())
        logWriter.write("\n")
        logWriter.flush()

# This is gotten from http://stackoverflow.com/questions/375427/non-blocking-read-on-a-subprocess-pipe-in-python
def executeCommand(cmd, logWriter):
   myPrint(cmd + "\n", logWriter)
    p = Popen(cmd, stdout=PIPE, bufsize=4096, close_fds=ON_POSIX, shell=True)
    q = Queue()
    t = Thread(target=enqueue_output, args=(p.stdout, q))
    t.daemon = True # thread dies with the program
    t.start()

    # read line without blocking
    while t.isAlive() or not q.empty():
        try:
            line = q.get_nowait() # or q.get(timeout=.1)
        except Empty:
            pass # Do nothing
        else: # If there is a line, then print it 
            if logWriter is not None:
                myPrint(line, logWriter)
        # Sleep to prevent python from using too much cpu
        time.sleep(0.05)

if __name__ == "__main__":
    freeze_support()
    convertPool = Pool(multiprocessing.cpu_count())
    # Now let's smooth and threshold all the masks
    for foo in bar:
        threshSmoothCmd = "ConvertImage.exe -i " + foo + " -o " + foo
        myPrint(threshSmoothCmd + "\n", None)
        convertPool.apply_async(executeCommand,(threshSmoothCmd, None,))

    convertPool.close()
    convertPool.join()
print "Finished processing"

ConvertImage.exe は、私が自分で作成した実行可能ファイルです。foo と bar は単なるプレースホルダーです。Linux では、これにより multiprocessing.cpu_count() 個の ConvertImage.exe プロセスが起動され、すべての ConvertImage.exe プロセスが終了すると Finished processing が出力されます。Windows では、これによりすぐに len(bar) ConvertImage.exe プロセスが開始され、すぐに Finished processing が出力されて終了します。Windows バージョンを Linux バージョンのように動作させるにはどうすればよいですか?

4

1 に答える 1

0

私はこれを理解し、それは正しく機能していました.いくつかのインポートを忘れたため、私のサンプルプログラムは間違って投稿され、それが記述された動作を引き起こしました. すべてのインポートを正しく行った後、この例は Windows と Linux で正常に動作しました。

于 2012-07-16T18:07:28.653 に答える