在python中获取一条线之前的路径

2024-10-01 02:20:31 发布

您现在位置:Python中文网/ 问答频道 /正文

给定一个带有嵌套if else语句的python函数,我们如何获得到达一行的路径

def function():
   if condition1:
      if condition2:
         sth
      else:
         get_path()
   else:
      sth

在本例中,当函数function运行时,get_path()应该返回类似function.condition1.not(condition2)的内容

我不想自己构建路径,我考虑过使用模块inspect并查看堆栈帧中存储的内容,但我认为需要进行一些处理才能获得路径。有没有更简单的办法


Tags: path函数路径内容getifdefnot
2条回答

您基本上希望跟踪函数执行过程中发生的事情;您只需使用traceread more here),如下所示:

import sys
import trace

# create a Trace object, telling it what to ignore, and whether to
# do tracing or line-counting or both.
tracer = trace.Trace(
    ignoredirs=[sys.prefix, sys.exec_prefix],
    trace=0,
    count=1)

def test():
    if True:
        if False:
            print('one')
        else:
            print('two')

# run the new command using the given tracer
tracer.run('test()')

# make a report, placing output in the current directory
r = tracer.results()
r.write_results(show_missing=True, coverdir=".")

输出:

>>>>>> import sys
>>>>>> import trace

       # create a Trace object, telling it what to ignore, and whether to
       # do tracing or line-counting or both.
>>>>>> tracer = trace.Trace(
>>>>>>     ignoredirs=[sys.prefix, sys.exec_prefix],
>>>>>>     trace=0,
>>>>>>     count=1)

>>>>>> def test():
           if True:
               if False:
                   print('here')
               else:
    1:             print('here2')

       # run the new command using the given tracer
>>>>>> tracer.run('test()')

       # make a report, placing output in the current directory
>>>>>> r = tracer.results()
>>>>>> r.write_results(show_missing=True, coverdir=".")

上面将生成带有跟踪结果的.cover文件;否则,你就得玩弄琴弦和/或一系列动作,并以此为路径

最简单的方法:

def function():
    path = 'function'

    if condition1:
        path += '.condition1'

        if condition2:
            path += '.condition2'
        else:
            path += '.not(condition2)'
    else:
        path += '.not(condition1)'

这是一个例子;它不具备可扩展性,但能满足微小的需求

这个简单的方法,只适用于小路径和用户定义,不需要库。你可以创建一个列表,并在该列表中附加if条件的相应标记(仅当条件满足时才会附加)。因此,任何时候你觉得可以按事件发生的顺序打印列表

相关问题 更多 >