|
Description:
A little script for those of us who prefer tabs over spaces.
Source: Text Source
import sys
import os
from stat import ST_MODE
import tokenize
__VERSION__ = "0.5.1"
def tabify(filename):
mode = os.stat(filename)[ST_MODE]
os.rename(filename, filename+".bak")
infile = file(filename+".bak")
outfile = file(filename,"w")
tokens = tokenize.generate_tokens(infile.readline)
text = []
indent = 0
minlineno = 0
for (toktype, token, start, end, line) in tokens:
y, x = end
if toktype == tokenize.INDENT:
indent += 1
elif toktype == tokenize.DEDENT:
indent -= 1
elif y > minlineno:
minlineno = y
text += "%s%s\n" % ("\t"*indent,line.strip())
outfile.write("".join(text))
infile.close()
outfile.close()
os.chmod(filename, mode)
def main():
if len(sys.argv) < 2:
print "usage: %s file1.py file2.py ..." % sys.argv[0]
sys.exit()
for filename in sys.argv[1:]:
tabify(filename)
if __name__ == "__main__":
main()
Discussion:
Since I always use tabs to indent, it becomes a pain to modify Python source files from others who use spaces. Python includes a small script to `untabify` to convert tab indented source code to spaced one, but no utility the other way around; I hope this little script will fill that gap.
You can use this script by supplying the names of the files in the command line (e.g):
$ python tabify hello.py world.py
The script creates backups of the original files, by adding `.bak` to their filenames.
|