2014-03-27 237 views
1

我試圖用if語句啓動一個進程for item in list。 if語句(如果滿足條件)將調用傳遞2個參數的函數。該函數然後遍歷另一個列表,爲列表中的每個列表運行子進程調用。現在出於某種原因,我沒有從子流程中獲取任何輸出。如果我在命令行中運行相同的命令,它可以正常工作,並且在我開始執行多處理器之前,它工作正常。任何人都可以解釋發生了什麼?在循環問題中的多處理

這是函數如何被調用。

userlist = (name1, name2, name3) 
if condition == True: 
    for user in userlist: 
     p = multiprocessing.Process(target=tllocaltF, args=(serverlist, user)) 
     jobs.append(p) 
     p.start() 

這是它被調用函數:

def tllocaltF(domain, user): 
#function iterates list of target users locally 
    print (domain,user) #this prints out the username and domain as expected 
    print "Targeted Users Found On LocalHost\n" 
    try: 
     out = subprocess.check_output(["tasklist", "/V", "/FO", "List", "/FI", "USERNAME eq {0}\\{1}" .format(domain, user)], stderr=subprocess.STDOUT) 
     users = [item for item in out.split() if domain in item and user in item] 
     sortedl = set(users) 
     print sortedl #this is printing set([]) 
     for item in sortedl: 
      print item 
    except CalledProcessError as e: 
     errormessage = e.output 
     print errormessage 

    print "\nCompleted"  
+0

如果我'打印出'我收到以下信息:信息:沒有任何任務符合指定的標準正在運行。那麼多進程實例對命令做了什麼? – iNoob

+0

你如何運行這段代碼?即在什麼環境下?在某些環境下,與子進程中的打印有關的各種錯誤/問題。 – roippi

+0

我在Windows 7上運行代碼 – iNoob

回答

1

,你不會看到從通過multiprocessing.Subprocess()調用函數的任何輸出,因爲該功能啓動一個完全獨立的過程,有它自己的標準輸入和標準輸出,它們沒有連接到父進程的命令提示符/終端。您有幾個選項:

1)將您的打印語句更改爲tllocaltF()以寫入臨時文件而不是打印。這不是一個長期的解決方案,但可以是一個有用的調試步驟,以確保您的子進程代碼實際上按照您認爲的方式執行。你應該能夠看到你的子進程丟棄文本文件而不是打印到標準輸出。如果你沒有看到文本文件出現,那麼你的函數可能根本就沒有執行。

2)實現類似於this的方法,它非常類似於this SO question,以捕獲子進程的輸出。

3)將您的子過程的輸出放在pipe or queue上,以便由主進程檢索並打印出來。

4)由於你推出的子進程來處理迭代的部分,你可能還需要考慮使用multiprocessing pool

import multiprocessing 
import functools 

if condition == True: 

    # use functools.partial() to create a new function that always has the same first 
    # argument - it seems to me that your code always calls tllocaltF() with the same 
    # serverlist argument, so we're going to create a new function that doesn't need 
    # serverlist to be explicitly passed every time - this is required to use 
    # multiprocessing.map() 

    single_argument_function = functools.partial(tllocaltF, serverlist) 

    pool = multiprocessing.Pool() 
    results = pool.map(single_argument_function, userList) # blocking call 

    # don't forget to clean up 
    pool.close() 
    pool.join() 

該代碼段會做你已經做同樣的事情,但是啓動子進程的這種方法將緩解你的整個輸出問題 - 你的子進程(當以這種方式啓動時)將使用與父進程相同的stdout。如果您不想等待結果,可以使用multiprocessing.map_async()(它是非阻塞的),並稍後檢查結果對象。