how to detect comment in source code file ?

Vincent Vande Vyvre vincent.vandevyvre at swing.be
Thu Sep 5 01:33:18 EDT 2013


Le 04/09/2013 08:05, vnkumbhani at gmail.com a écrit :
> how works python interpreter for finding comment ?
> if possible find nested comment ?
If you need to find it yourself, you can use the module tokenize.

ex.:
---------------------------------------------------------------
import tokenize
from StringIO import StringIO

script = "# importing comment\nfrom foo import baz"\
"if baz.vers < 2:\n    AUTO = False # Retrocompatibility"

def find_comment():
     print script
     cmt = tokenize.COMMENT
     tokens = tokenize.generate_tokens(StringIO(script).readline)
     for typ, _, begin, _, _ in tokens:
         if typ == cmt:
             print 'Find comment line %s at column %s' % begin

find_comment()
---------------------------------------------------------------

(for Python 3 import StringIO from io)

-- 
Vincent V.V.
Oqapy <https://launchpad.net/oqapy> . Qarte 
<https://launchpad.net/qarte> . PaQager <https://launchpad.net/paqager>



More information about the Python-list mailing list