Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #41349 > unrolled thread
| Started by | Mark Shroyer <mshroyer@awaredigital.com> |
|---|---|
| First post | 2013-03-17 02:23 -0400 |
| Last post | 2013-03-17 02:23 -0400 |
| Articles | 1 — 1 participant |
Back to article view | Back to comp.lang.python
This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by
below is the oldest one visible, not the original post.
RE: How to automatically get the indent level from code? Mark Shroyer <mshroyer@awaredigital.com> - 2013-03-17 02:23 -0400
| From | Mark Shroyer <mshroyer@awaredigital.com> |
|---|---|
| Date | 2013-03-17 02:23 -0400 |
| Subject | RE: How to automatically get the indent level from code? |
| Message-ID | <mailman.3384.1363501486.2939.python-list@python.org> |
I realize this isn't yet precisely what you're asking for, but look at the inspect and ast modules:
import ast, inspect
def indent_level():
lineno = inspect.currentframe().f_back.f_lineno
with open(__file__) as source_file:
tree = ast.parse(source_file.read(), filename=__file__)
for node in ast.walk(tree):
if hasattr(node, 'lineno') and node.lineno == lineno:
return node.col_offset
def example_usage():
print("first indent_level() = {0}".format(indent_level()))
if True:
print("second indent_level() = {0}".format(indent_level()))
if __name__ == '__main__':
example_usage()
The indent_level function above returns the textual column offset rather than the logical block level you're asking for, e.g.:
first indent_level() = 4
second indent_level() = 8
But hopefully it's a start.
Mark
-----Original Message-----
From: Python-list [mailto:python-list-bounces+mshroyer=awaredigital.com@python.org] On Behalf Of Peng Yu
Sent: Sunday, March 17, 2013 12:53 AM
To: python-list@python.org
Subject: How to automatically get the indent level from code?
Hi,
I want to get the indent level within the code. For example, I want to
print 1 within the while loop as the line is indented 1 level. Is it
possible to get it within python?
while 1:
#print the level of indent, which is 1 here.
--
Regards,
Peng
--
http://mail.python.org/mailman/listinfo/python-list
Back to top | Article view | comp.lang.python
csiph-web