Near the end of a recent blog post:
asciiflow.com: Draw flowcharts online, in ASCII
, I showed how this small snippet of Python code can be used to make a Python program usable as a component in a Unix pipeline:
for lin in sys.stdin: sys.stdout.write(process(lin))
Today I saw Raymond Hettinger (@raymondh)'s tweet about the -t and -tt command line options of Python:
#python tip: In Python 2, the -tt option raises an error when you foolishly mix spaces and tabs. In Python 3, that is always an error.That made me think of writing a simple Python 2 tool to change the tabs in a Python file to spaces. Yes, I know it can be easily done in Unix or Windix  with any of sed / awk / tr etc. That's not the point. So here is tabtospaces.py:
import sys for lin in sys.stdin: sys.stdout.write(lin.replace("\t", " "))[ Note: this code converts each tab into 4 spaces. It can be parameterized by passing a command-line option that specifies the number of spaces, such as 4 or 8, and then replacing each tab with that many spaces. Also note that I have not tested the program on many sets of data, just one for now. ]
I created a simple Python file, test1.py, that has mixed tabs and spaces to use as input to tabtospaces.py. Then I ran the following commands:
$ py -tt test1.py File "test1.py", line 4 print arg, ^ TabError: inconsistent use of tabs and spaces in indentation $ py tabtospaces.py < test1.py > test2.py $ py -tt test2.py 0 1 2 3 4 5 6 7 8 9which shows that tabtospaces.py does convert the tabs to spaces.
And you can see from this diff that the original test1.py and the test2.py generated by tabtospaces.py, differ only in the use of tabs vs. spaces:
$ fc /l test1.py test2.py Comparing files test1.py and TEST2.PY ***** test1.py for arg in args: print arg, ***** TEST2.PY for arg in args: print arg, *****
 Windix is the latest upcoming Unix-compatible OS from M$, due Real Soon Now. You heard it here first - TM.
- Vasudev Ram - Online Python training and programming Dancing Bison EnterprisesSignup to hear about new software products or info-products that I create. Posts about Python Posts about xtopdf Contact Page