擅长:python、mysql、java
<p>我可以使用inspect.getouterframes()功能。这假设缩进使用4''字符而不是'\t'字符。在</p>
<pre><code>import inspect
def getIndentationLevel():
# get information about the previous stack frame
frame, filename, line_number,function_name, lines, index = inspect.getouterframes(inspect.currentframe())[1]
# count the number of characters in the line
original_length = len(lines[0])
# trim the line of left spaces and record the new length
new_length = len(lines[0].lstrip())
# take the difference between the two values and divide by 4 to get the level number
return int((original_length - new_length) / 4)
</code></pre>