2014-03-27 5 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() 

는 호출되는 함수이다 :이 함수는 완전히 별도의 프로세스를 시작하기 때문에 당신은 multiprocessing.Subprocess() 통해 호출 함수에서 출력을 볼 수 없습니다

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

만약 내가 출력하면 다음과 같은 결과를 얻습니다 : INFO : 지정한 기준에 맞는 작업이 실행되고 있지 않습니다. 그렇다면 다중 프로세스 인스턴스가 명령에 대해 무엇을하고 있습니까? – iNoob

+0

이 코드를 어떻게 실행하고 있습니까? 즉 어떤 환경에서? 특정 환경에서 하위 프로세스의 인쇄와 관련된 다양한 버그/문제점이 있습니다. – roippi

+0

Windows 7에서 코드를 실행하고 있습니다. – iNoob

답변

1

그 상위 프로세스의 명령 프롬프트/터미널에 연결되지 않은 자체 stdin 및 stdout을가집니다. 몇 가지 옵션이 있습니다.

1) tllocaltF()의 인쇄 명령문을 인쇄하는 대신 임시 파일에 쓰십시오. 이것은 장기적인 솔루션은 아니지만, 서브 프로세스 코드가 실제로 생각대로 실행되고 있는지 확인하는 데 유용한 디버깅 단계가 될 수 있습니다. stdout으로 인쇄하는 대신 텍스트 파일을 삭제하는 하위 프로세스를 볼 수 있어야합니다. 텍스트 파일이 표시되지 않으면 함수가 전혀 실행되지 않을 수 있습니다.

2) 서브 프로세스의 출력을 캡처하려면 this SO question과 매우 유사한 this과 같은 메소드를 구현하십시오.

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() 

이 코드는 이미하고 있던 같은 일을 할 것입니다, 그러나 서브 프로세스를 시작하는이 방법은 전체 출력 문제를 완화합니다. 서브 프로세스 (이 방법으로 시작될 때)는 부모 프로세스와 동일한 표준 출력을 사용합니다. 결과를 기다리지 않으려는 경우 멀티 프로세싱 .map_async() (비 블로킹)를 사용하고 나중에 결과 개체를 확인할 수 있습니다.