Python - 打印出可视递归跟踪

时间:2014-10-08 15:46:14

标签: python recursion

我有这个代码正在进行递归,但我希望能够观察递归但是说明每次递归的深度以及它何时返回。只是简单的事情如下所示。不知道我需要在哪里放置空格或制表符来实现这一点,我正在使用字符串map_str,然后在最后打印出来。请参阅输出的代码和示例。

def get_process_parents(batchDate, late_process):
    global late_parents
    global map_str
    process_depends = []
    #logging.info('late_process: %s ' % late_process)
    process_depends = getprocessDependencies(batchDate, late_process)
    late_parents[late_process.get('name')] = process_depends
    map_str += (' %s ---> %s \n------>\n' % (late_process.get('name'), process_depends))
    #logging.info('Late_process Name: %s ---> Depends: %s ' % (late_process.get('name'),process_depends))
    if not process_depends:
        #logging.info('No more depends: %s' % late_process.get('name'))
        late_parents_process.add(late_process.get('name'))
        map_str += (' %s ---> %s\n ---->\n' % (late_process.get('name'), process_depends))
    else:
        for process_depend in process_depends:
            process = getprocessByName(batchDate, process_depend)
            #logging.info('process_depend %s --> state: %s ' % (process_depend, process.get('state')))
            if process.get('state') == 'Done':
                #logging.info('process depend DONE: %s' % process_depend)
                map_str += (' %s Status: %s\n ---->\n' % (process_depend, process.get('state')))

            else:
                late_parents_process.add(process.get('name'))
                get_process_parents(batchDate, getprocessByName(batchDate,process_depend))

输出:

我希望它看起来像什么

 Process_name ----> ['process dependencies 1', 'process dependencies 2'] 
------>process dependencies 1 ---->  [process dependencies 3, dependencies 4] 
       ------>dependencies 3 -----> []
       ------>dependencies 4 -----> []
------>process dependencies 2 ---->  [process dependencies 5] 
       ------>process dependencies 5 -----> [process dependencies 6] 
              ----->process dependencies 6 -----> [] 

1 个答案:

答案 0 :(得分:1)

你能改变功能签名吗?如果是这样,那么最简单的方法是将函数定义为:

def get_process_parents(batchDate, late_process, depth=0):

然后在嵌套调用中使用

get_process_parents(batchDate, getprocessByName(batchDate,process_depend), depth + 1)

然后,要缩进,您可以使用:

print '\t' * depth + ('%s---->... # etc, etc

如果可以避免,请注意不要使用map_str的全局。