2012-09-13 5 views
8

나는 재귀 적으로 호출되는 함수가 있으며 재귀의 현재 수준을 알고 싶습니다. 아래의 코드는 내가 그것을 계산하는 데 사용하는 방법을 보여 주지만 예상 된 결과를 제공하지는 않습니다.파이썬에서 재귀 호출 수준 찾기

예. : 내가 부를 것이다, 내 디렉토리 구조에서 :

디렉토리 구조는 디렉토리를 재귀 수준을 인쇄, 디렉토리 경로 감안할 때 :

import os 
    funccount = 0 

    def reccount(src): 
     global funccount 
     print "Function level of %s is %d" %(src, funccount) 

    def runrec(src): 
     global funccount 
     funccount = funccount + 1 
     lists = os.listdir(src) 
     if((len(lists) == 0)): 
      funccount = funccount - 1 
     reccount(src) 
     for x in lists: 
      srcname = os.path.join(src, x) 
      if((len(lists) - 1) == lists.index(x)): 
        if (not(os.path.isdir(srcname))): 
         funccount = funccount - 1 
      if os.path.isdir(srcname): 
       runrec(srcname) 

    runrec(C:\test) 

문제 : 시스템 경로에 대한 재귀 수준을 찾으려면 함수 "reccount (Test)"(함수는 MainFolder의 경로와 함께 호출됩니다). 각 폴더에 대한 재귀 호출 수준을 알고 싶습니다. (디렉토리에만 해당)

Test: 
    |----------doc 
    |----------share 
       |----------doc 
          |----------file1 
    |----------bin 
       |----------common 
          |----------doc 
    |----------extras 
    |----------file2 

내가 프로 시저를 호출하면, 다음과 같은 결과를 얻을 : 당신이 볼 수 있듯이

Function level of C:\test is 1 
    Function level of C:\test\bin is 2 
    Function level of C:\test\bin\common is 3 
    Function level of C:\test\bin\common\doc is 3 
    Function level of C:\test\doc is 3 
    Function level of C:\test\extras is 3 
    Function level of C:\test\share is 4 
    Function level of C:\test\share\doc is 5 

, 그것은 빈/일반/문서에 대한 결과를 출력 할 때, 그것은 3을 대신 출력을 4 및 이후의 모든 결과가 잘못되었습니다.

+0

왜 부정적 수 :

def runrec(src, level=1): # ... runrec(new_src, level + 1) 

그런 식으로, 당신은 전역 변수가 필요하지 않습니다? – sarbjit

답변

29
def some_method(data, level=0): 


    some_method(..., level=level+1) 


if __name__ == '__main__': 
    some_method(my_data) 
3

왜 매개 변수에 재귀 수준을 저장하지 않습니까?

def reccount(src, level): 
    print "Function count of {} is {}".format(src, level) 
16
from inspect import getouterframes, currentframe 
import os 

def runrec(src): 
    level = len(getouterframes(currentframe(1))) 
    print("Function level of {} is {}".format(src, level)) 
    for x in os.listdir(src): 
     srcname = os.path.join(src, x) 
     if os.path.isdir(srcname): 
      runrec(srcname) 

runrec('C:\\test') 

Function level of C:\test is 1 
Function level of C:\test\bin is 2 
Function level of C:\test\bin\common is 3 
Function level of C:\test\bin\common\doc is 4 
Function level of C:\test\doc is 2 
Function level of C:\test\extras is 2 
Function level of C:\test\share is 2 
Function level of C:\test\share\doc is 3 
+2

Andreas의 답변이 OP의 확실한 선택이지만 +1은 추가 매개 변수가 필요없는 솔루션입니다. extra param의 번거 로움없이 재귀 함수에서 중첩 된 디버그 정보를 인쇄하는 데 매우 유용합니다. – Davide

+0

다른 함수에서이 함수를 호출하면 숫자가 증가하고 재귀 깊이는 동일하게 유지되며 매개 변수 기반 방식에는이 결함이 없습니다. – Bob