How can I strip comments and doc strings from python source code? [closed]
Asked Answered
S

2

6

Is there a program which I can run like this:

py2py.py < orig.py > smaller.py

Where orig.py contains python source code with comments and doc strings, and smaller.py contains identical, runnable source code but without the comments and doc strings?

Code which originally looked like this:

#/usr/bin/python
"""Do something
blah blah...
"""

# Beware the frubnitz!
def foo(it):
    """Foo it!"""
    print it  # hmm?

Would then look like this:

def foo(it):
    print it
Stepson answered 25/10, 2009 at 17:43 Comment(0)
R
8

This Python minifier looks like it does what you need.

Rasping answered 25/10, 2009 at 17:43 Comment(3)
Excellent. 'minify' was the magic word.Stepson
doesn't work for me. Is it up to date?Sharasharai
@NathanB No, it's not up to date. If you take look, it says "Released: May 31, 2014", it hasn't been updated in nearly 10 years. The key is that the term for this type of program is "minifier", so if you search for "python minifier", you can find other more up to date ones like this one: pypi.org/project/python-minifierRasping
H
3

I recommend minipy. The most compelling reason is that it does proper analysis of the source code abstract syntax tree so the minified code is much more accurate. I've found that the more well known pyminifier tends to generate code with undefined symbol errors, misinterpreted tuples, etc. I also got a few percent better compression results with minipy. A minor benefit of minipy is that it's less than half the code size of pyminifier. It's also easier to manage and integrate into a build pipeline because it's a single standalone python file.

Highmuckamuck answered 25/10, 2009 at 17:43 Comment(2)
Upvoted, but do note that minipy only supports Python 2.Thuthucydides
@JohnMcGehee with a couple of trivial changes I was able to work around the most obvious python 2-isms and it now supports the python 3 code that I'm minifying. Here is the change: github.com/kanaka/minipy/commit/…Highmuckamuck

© 2022 - 2024 — McMap. All rights reserved.