2014-07-26 4 views
0

현재 멀티 스레딩에 대한 일부 작업을 수행하고 있으며 프로그램이 의도 한대로 작동하지 않는 이유를 파악하려고합니다.Python multithreading raw_input

def input_watcher(): 
    while True: 
    input_file = os.path.abspath(raw_input('Input file name: ')) 
    compiler = raw_input('Choose compiler: ') 

    if os.path.isfile(input_file): 

     obj = FileObject(input_file, compiler) 

     with file_lock: 
      files.append(obj) 

     print 'Adding %s with %s as compiler' % (obj.file_name, obj.compiler) 
    else: 
     print 'File does not exists' 

이것은 하나의 스레드에서 실행 중이고 두 번째 파일 객체를 추가하기 시작할 때까지 제대로 작동합니다.

콘솔로부터의 출력이다

Input file name: C:\Users\Victor\Dropbox\Private\multiFile\main.py 
Choose compiler: aImport 
Adding main.py with aImport as compiler 
Input file name: main.py updated 
C:\Users\Victor\Dropbox\Private\multiFile\main.py 
Choose compiler: Input file name: Input file name: Input file name: Input file name: 

입력 파일명 제가 제 이름을 추가하고, 컴파일러를 요청 번째 팝업 유지한다. 프로그램은 충돌 할 때까지 입력 파일 이름을 계속 인쇄합니다. '

나는 다른 스레드에서 실행되는 다른 코드가 있는데, 오류와 관련이 없다고 생각하지 않지만보고 싶으면 게시하고 게시 할 것입니다.

전체 코드 : 또한 Windows에서 multiprocessing.Process을 사용하는 동안, if __name__ == "__main__": 가드를 사용하지 않는 때문에 이런 일이

import multiprocessing 
import threading 
import os 
import time 


file_lock = threading.Lock() 
update_interval = 0.1 


class FileMethods(object): 
    def a_import(self): 
     self.mod_check() 




class FileObject(FileMethods): 
    def __init__(self, full_name, compiler): 

     self.full_name = os.path.abspath(full_name) 
     self.file_name = os.path.basename(self.full_name) 
     self.path_name = os.path.dirname(self.full_name) 

     name, exstention = os.path.splitext(full_name) 
     self.concat_name = name + '-concat' + exstention 

     self.compiler = compiler 
     self.compiler_methods = {'aImport': self.a_import} 

     self.last_updated = os.path.getatime(self.full_name) 

     self.subfiles = [] 
     self.last_subfiles_mod = {} 

    def exists(self): 
     return os.path.isfile(self.full_name) 

    def mod_check(self): 
     if self.last_updated < os.path.getmtime(self.full_name): 
      self.last_updated = os.path.getmtime(self.full_name) 
      print '%s updated' % self.file_name 
      return True 
     else: 
      return False 

    def sub_mod_check(self): 
     for s in self.subfiles: 
      if self.last_subfiles_mod.get(s) < os.path.getmtime(s): 
       self.last_subfiles_mod[s] = os.path.getmtime(s) 
       return True 

     return False 


files = [] 


def input_watcher(): 
    while True: 
     input_file = os.path.abspath(raw_input('Input file name: ')) 
     compiler = raw_input('Choose compiler: ') 

     if os.path.isfile(input_file): 

      obj = FileObject(input_file, compiler) 

      with file_lock: 
       files.append(obj) 

      print 'Adding %s with %s as compiler' % (obj.file_name, obj.compiler) 
     else: 
      print 'File does not exists' 


def file_manipulation(): 
    if __name__ == '__main__': 
     for f in files: 
      p = multiprocessing.Process(target=f.compiler_methods.get(f.compiler)()) 
      p.start() 
      #f.compiler_methods.get(f.compiler)() 

def file_watcher(): 
    while True: 
     with file_lock: 
      file_manipulation() 
     time.sleep(update_interval) 


iw = threading.Thread(target=input_watcher) 
fw = threading.Thread(target=file_watcher) 

iw.start() 
fw.start() 
+1

문제가 단일 스레드 환경에서 발생하지 않습니다. 단 하나의 스레드로 당신을 위해 일어날 수 있습니까? input_watcher가 호출되는 방식과 실행중인 다른 스레드와 어떻게 관련되는지를 알아야합니다. – dano

+0

전체 코드가 – VictorVH

답변

1

. Windows는 생성 된 하위 프로세스에서 모듈을 다시 가져와야하므로 입력을 처리하고 파일을 보는 새 스레드를 계속 생성합니다. 이것은 물론 재앙을위한 처방입니다. 이 문제를 해결하기 위해이 작업을 수행합니다 :

if __name__ == "__main__": 
    iw = threading.Thread(target=input_watcher) 
    fw = threading.Thread(target=file_watcher) 

    iw.start() 
    fw.start() 

는 더 많은 정보를 위해 multiprocessing docs 섹션은 "주요 모듈의 안전 가져 오기"를 참조하십시오.

file_watcher도 실제로 원하는대로하고 있지 않습니다. 이미 처리 한 파일에 대해 프로세스를 다시 생성합니다.하지만 원래의 질문과 관련이 없습니다.

+0

으로 추가되었습니다. 방금 시도했지만 효과가있었습니다. 방금 몇 가지 질문이 있습니다. – VictorVH

+0

filemanipulation 내부에서 프로세스를 생성하는 곳에서 이미 if __name == "__main__"검사를 수행합니다. 왜 스레드로 처리해야합니까? – VictorVH

+0

또한 file_watcher의 요점은 파일이 업데이트되었는지 확인하는 새로운 프로세스를 생성하는 것이며 새로운 프로세스가 있으면 해당 작업을 수행하는 것입니다. 이것이 잘못된 방식인가? – VictorVH