2013-05-14 3 views
0

나는 이것에 대해 약간의 연구를 해왔지만, 파이썬 자체가 아닌 다른 프로그램이 실행되고 있는지를 알아내는 방법을 다루는 것으로 보인다.프로세스가 여전히 파이썬에서 실행 중인지 확인하는 방법?

그래서 현재 셰이프 파일의 줄 집합 주위에 버퍼를 생성하는 코드를 작성하고 있습니다. 20 개의 쉐이프 파일과 내부에 최대 4000 개의 라인을 포함하는 배치 프로세스입니다. 이 프로세스는 정말로 오랜 시간이 걸리고 있으며 실제로 작동하는지 궁금해지기 시작했습니다. 필자는 보통 코드의 진행 상황을 추적하기 위해 print 문을 사용합니다. 그러나이 경우 함수를 수행하기 위해 ArcGIS를 호출하므로 모든 행이 처리 된 후에도 쓸 수있는 유일한 print 문은 처리 된 것입니다. 달리는.

프로세스가 여전히 진행 중인지 알아볼 수있는 방법이 있습니까 (작업 관리자가 작동 중지되었는지 확인하는 것 이외의 방법)?

나는 그것을 할 수있는 미친 방법 (이 같은 것이 가능한지 전혀 모른다) : 스크립트가 실행을 마치지 않은 한 모든 X 분마다 txt 파일에 뭔가를 쓰는 것과 같은 것을 생각하고있었습니다. .

감사합니다 !!!!

내 코드 :

def Buffer30m(self,InputFile,OutputBuffer, size):  
    arcpy.Buffer_analysis(InputFile,OutputBuffer,size,"FULL","ROUND","NONE","#") 


TheList=os.listdir(SSFlinespath) #read the files in the folder 
os.mkdir(SSFlines+"SSFbuffers"  #create folder for the output 
SSbuff=SSFlinespath+"SSFbuffers/" #select the folder as destination 
try: 
    size=30 
    for TheFile in TheList:           #Identify each file 
     TheFileName, TheFileExtension = os.path.splitext(TheFile) #Break up the file name 
     if (TheFileExtension==".shp"):        #Identify the shapefiles 
      TheLines=SSFlines+TheFile 
      ##Generate a 30m buffer around the lines 
      TheBuffer=SSFbuff+TheFileName+"_buff30.shp" 
      TheStepBuffer.Buffer30m(TheLines,TheBuffer,size) 
      print "SSF buffer done" 
except Exception as TheError: 
    print "Error with the SSF forest area calculation" 
    print TheError 

UPDATE 부분 솔루션, 전체 코드와 새로운 이슈 :

나는 한번도 언급 한 기능 위대한 작품 qwwqwwq의 제안을 적용했다. 이제는 나머지 스크립트를 실행할 때 (이전에 보여준 내용은 일부 였기 때문에 많은 것을 읽을 필요가 없었습니다) 다른 기능 중 일부는 작동하지 않습니다. 여기

는 전체 스크립트입니다

class StepBuffer: 
def GetPairInfo (self, MainFile, SourceFile, WantFields, SSF): 
    fields= WantFields #Fields I will keep 
    ##Extract the info and add to the main table 
    if SSF==False: 
     GRHE_proj.GetFieldInfo(MainFile,SourceFile,"Pair", "Pair", fields) 
    elif SSF==True: 
     GRHE_proj.GetFieldInfo(MainFile,SourceFile,"SAMPLEID", "SAMPLEID", fields) 

def Buffer30m(self,InputFile,OutputBuffer, size): 
    arcpy.Buffer_analysis(InputFile,OutputBuffer,size,"FULL","ROUND","NONE","#") 

def AreaBuff (self,InputFile, OutputTable):  
    arcpy.CalculateAreas_stats(InputFile,OutputTable) 

def AreaForest (self,BufferFile,ForestFile, OutputTable, SSF): 
    if SSF==False: 
     arcpy.TabulateIntersection_analysis(BufferFile,"Pair",ForestFile,OutputTable,"type","#","#","HECTARES") 
    elif SSF==True: 
     arcpy.TabulateIntersection_analysis(BufferFile,"SAMPLEID",ForestFile,OutputTable,"type","#","#","HECTARES") 



TheList=os.listdir(SSFlinespath) #read the files in the folder 
os.mkdir(SSFlines+"SSFbuffers"  #create folder for the output 
SSbuff=SSFlinespath+"SSFbuffers/" #select the folder as destination 

try: 
    size=30 
    for TheFile in TheList:           #Identify each file 
    TheFileName, TheFileExtension = os.path.splitext(TheFile) #Break up the file name 
    if (TheFileExtension==".shp"):        #Identify the shapefiles 
     TheLines=SSFlines+TheFile 
     ##Generate a 30m buffer around the lines 
       t = threading.Thread(target=TheStepBuffer.Buffer30m, args=(TheLines,TheBuffer,size)) 
       t.start() 
       while (t.is_alive()): 
        time.sleep(2) ## sleep so that we don't execute the print statement too often 
        print "I'm alive!"     
       print "SSF buffer done" 


       ##Calculate area of buffer 
       TableAreaBuff=OutputTables+TheFileName+"_Area_Buffers.dbf"   
       TheStepBuffer.AreaBuff(TheBuffer,TableAreaBuff) 
       print "SSF area buffer done" 

       ##Calculate the area of the forest inside the buffer 
       TableAreaFor=OutputTables+TheFileName+"_Area_forest.dbf" 
       TheStepBuffer.AreaForest(TheBuffer,ForestPath,TableAreaFor,True) 
       print "SSF area forest done" 

       ##Add info of the area of the buffer to the buffer layer 
       TheStepBuffer.GetPairInfo(TheBuffer,TableAreaBuff, "F_AREA",True) 

       ##Add info of area of forest within the buffers to the buffer layer 
       TheStepBuffer.GetPairInfo(TheBuffer,TableAreaFor,["Area","Percentage"],True) 
       print TheFileName+"Done" 
    except Exception as TheError: 
     print "Error with the SSF forest area calculation" 
     print TheError 
     TheErrorFile.writelines(format(TheError)+"\n") 

특히, 오류가 얻을 때 나타나는에 :

arcgisscripting.ExecuteError: 
Traceback (most recent call last): 
File "c:\program files (x86)\arcgis\desktop10.1\ 
ArcToolbox\Scripts\CalculateAreas.py", line 76, in <module> 
setupCalcAreas() 
File "c:\program files (x86)\arcgis\desktop10.1\ArcToolbox\Scripts\CalculateAreas.py", line 31, in setupCalcAreas 
calculateAreas(inputFC, outputFC) 
File "c:\program files (x86)\arcgis\desktop10.1\ArcToolbox\Scripts\CalculateAreas.py", line 55, in calculateAreas 
cnt = UTILS.getCount(inputFC) 
File "c:\program files (x86)\arcgis\desktop10.1\ArcToolbox\Scripts\SSUtilities.py", line 502, in getCount 
return int(countObject.getOutput(0)) 
File "C:\Program Files (x86)\ArcGIS\Desktop10.1\arcpy\arcpy\arcobjects\arcobjects.py", line 986, in getOutput ... (truncated) 
return convertArcObjectToPythonObject(self._arc_object.GetOutput(*gp_fixargs(args))) ... (truncated) 
File "C:\Users\Noelia Volpe\Dropbox\Project\analisis\Python_Codes\Scripts\MovementPref\volpe_project_v2.py", line 464, in <module> 
    TheStepBuffer.AreaBuff(TheBuffer,TableAreaBuff) 
File "C:\Users\Noelia Volpe\Dropbox\Project\analisis\Python_Codes\ReUsable\Movement_preferences.py", line 58, in AreaBuff 
    arcpy.CalculateAreas_stats(InputFile,OutputTable) 
File "C:\Program Files (x86)\ArcGIS\Desktop10.1\arcpy\arcpy\stats.py", line 1564, in CalculateAreas 
    raise e 

사람이 무슨 일이 수도 알고 있나요 :

TheStepBuffer.AreaForest(TheBuffer,ForestPath,TableAreaFor,True) 

이 오류를 생산 이 오류의 출처가 될까요? 감사합니다.

+1

변수 이름은 [Python 스타일 가이드] (http://www.python.org/dev/peps/pep-0008/#method-names-and-instance-variables)를 따라야합니다. lower_case_with_underscores ''CapWords가 아님 '-이 명명 규칙은 클래스에 사용되며 다른 클래스를 혼동시킬 수 있습니다. –

+0

오, 죄송합니다. 이것이 내가 파이썬 수업에서 생각한 방식입니다. 그들은 명명 규칙을 언급하지 않았다 :/나는 나의 예에서 그것을 바꿔야 하는가? 아니면 지금 당장 그대로 둘 수 있을까요? – Noelia

+0

'다른 프로그램이 실행 중일 때, 파이썬 자체가 아니라면'당신이 의미하는 것이 명확하지 않습니다. 프로세스가 실행됩니다.파이썬은 언어입니다. 'ANOTHER' 프로세스가 아닌 프로세스가 실행 중인지 파악하고 싶다면 프로세스 자체가 실행 중인지 여부를 알고 싶어합니다. 글쎄, 그건 마치 내가 살아 있는지 묻는 것과 같다. 당신이 그 질문을 할 수 있다면, 당신은 그렇습니다. Cogito 에고 총계. – shx2

답변

2

내가 멀티 스레딩을 사용하려고 할 것입니다 :

import threading 
import time 
t = threading.Thread(target=TheStepBuffer.Buffer30m, args=(TheLines,TheBuffer,size)) 
t.start() 

while (t.is_alive()): 
    time.sleep(2) ## sleep so that we don't execute the print statement too often 
    print "I'm alive!" 

print 문을 실행, 그것은 여전히 ​​목표 기능을 실행하고 있는지 확인하기 위해 해당 스레드를 모니터링 할 기능 TheStepBuffer.Buffer30m, 제어 스레드를 실행 스레드 모두가 건강하다는 것을 알려주십시오.

+0

와우! 감사! 그게 바로 내가 찾던 해결책의 종류입니다. 그래도 질문이 있습니다. 나중에 스레드를 "끝내야"할 필요가 있습니까? (나는 우리가't.start()'로 시작했기 때문에 이것을 가정하고있다). 나는 스크립트에서 다른 arcpy 함수를 실행하려고 할 때 나에게 오류가 발생하기 때문에 [위의 질문에 대한 편집을 참조하십시오] 그리고 우리가 만든 스레드가 여전히 남아 있다는 사실 때문에 문제가되는지 궁금합니다. 약. 감사! – Noelia

+0

아니요 스레드를 종료 할 필요는 없습니다. 스레드는 두 개의 완전히 다른 프로그램 사이에서 앞뒤로 점프하는 프로세스라고 생각할 수 있습니다. 하나의 프로그램이 결론에 이르면 프로세스는 그 스레드에서 더 이상 시간을 소비하지 않으므로 효율적이지 않습니다. while 루프를 사용하여 스레드가 완료 될 때까지 기다렸다가 다른 작업을 수행하는 방법은 t.join()입니다. 귀하의 다른 오류가 관련이없는, arcpy 함수 중 하나처럼 그 추적에 따라 예외를 제기하는 것 같습니다. – qwwqwwq

+0

오! 내가 참조. 문제는 스레드를 수행 할 때만 해당 오류 메시지가 표시된다는 것입니다. 만약 내가 정상적으로 그것을 실행, 그래서 내가 추측하고있는 나머지 기능을 방해하는 일부 잔여 메모리가 있어야합니다. 내가 도와 줄 수있는 새로운 질문을해야한다고 생각하니? – Noelia

관련 문제