Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
shortening Python code
#8
You can also use textwrap to wrap the comments
#!/usr/bin/env python3
__doc__ = '''program wrapcomment.py
'''
__version__ = '0.0.1'
import argparse
import token
from tokenize import tokenize
import textwrap

def spit_comments(filename, width):
    with open(filename, 'rb') as ifh:
        for tok in tokenize(ifh.readline):
            if tok.type is token.COMMENT:
                s = textwrap.fill(tok.string, width=width)
                print(s)

if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        description = """\
Applies textwrap to all the comments in the argument file
and print these comments to stdout.
        """)
    parser.add_argument('filename', metavar='PYFILE',
                        help='python program to scan.')
    parser.add_argument('-w', '--width', metavar='WIDTH', type=int, default=70, help='textwrap width')
    args = parser.parse_args()
    spit_comments(args.filename, width=args.width)
Reply


Messages In This Thread
shortening Python code - by Skaperen - Oct-13-2022, 11:42 PM
RE: shortening Python code - by Larz60+ - Oct-14-2022, 03:07 AM
RE: shortening Python code - by Gribouillis - Oct-14-2022, 04:50 AM
RE: shortening Python code - by DeaD_EyE - Oct-14-2022, 08:13 AM
RE: shortening Python code - by snippsat - Oct-14-2022, 11:41 AM
RE: shortening Python code - by Skaperen - Oct-14-2022, 10:49 PM
RE: shortening Python code - by ndc85430 - Oct-15-2022, 04:14 AM
RE: shortening Python code - by Skaperen - Oct-15-2022, 10:33 PM
RE: shortening Python code - by Gribouillis - Oct-15-2022, 02:53 PM
RE: shortening Python code - by Skaperen - Oct-15-2022, 10:23 PM
RE: shortening Python code - by ndc85430 - Oct-23-2022, 07:01 AM
RE: shortening Python code - by wavic - Oct-23-2022, 08:53 AM
RE: shortening Python code - by Skaperen - Oct-23-2022, 10:54 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020