Monday, June 24, 2013

Python tips

To compile a python script without executing it, do
python -m py_compile my_script.py
[Courtesy: stackoverflow]

Wednesday, June 5, 2013

Installing Python regex on Ubuntu 12.04

To install the alternative regular expression module regex (which has richer Unicode support than re) for Python:
  • Install python-dev from the Software Center.
  • Download the archive, extract, and run sudo python setup.py install.

Monday, June 3, 2013

Downloading a blog on blogspot

This http://blogname.blogspot.com/search?max-results=N lists the latest N posts from the blog. Instead of N, type the number of posts. If your blog has less than 1000 posts, you can save this page: http://blogname.blogspot.com/search?max-results=1000

Thursday, May 2, 2013

Unicode tips for Python

  • To use non-Latin characters in regular expressions, use u'...' instead of r'...', even if you have to escape every backslash; e.g. the regex u'(?u)[०-९]\\s' matches a Devanagari digit followed by whitespace.
  • Remove zero-width joiners/non-joiners from Unicode text to get a normalized representation; otherwise words that are rendered the same in a browser/editor will be stored differently, and will not be equal on comparison; e.g. use the regex u'[\\u200D\\u200C]' and replace all matches with u'' (the empty string).

Friday, January 18, 2013

Shell script for scheduling jobs

Suppose you want to schedule many runs of myscript.py for different parameters, but never more than 8 at a time (e.g. because your machine has only 8 processor cores), then you can do:
 for param in `cat params.txt`; do  
   # wait if more than 7 jobs are running together  
   njobs=`ps aux | grep myscript | wc -l`  
   if [ $njobs -gt 8 ]; then          # 7 jobs + 1 grep  
     while [ $njobs -gt 8 ]; do  
       sleep 10  
     done  
   fi  
   python myscript.py param &     # schedule background job here  
 done  

Thursday, January 17, 2013

File compression in python

Normally, you can do
 f = open(fname, 'r')  
 data = f.read()  
 f.close()  
to read a file, and
 f = open(fname, 'w')  
 f.write(text)  
 f.close()  
to write a file.

To use gzip compression, do
 import gzip  
 f = gzip.open(fname, 'rb')  
 data = f.read()  
 f.close()  
to read a gzip-compressed file, and
 f = gzip.open(fname, 'wb')  
 f.write(data)  
 f.close()  
to write a gzip-compressed file.

To compress pickled objects, just use the file handle returned by gzip.open(); everything else remains the same.

(Courtesy Doug Hellmann.)

Sunday, November 18, 2012

Grep tips

To get all lines not beginning with a tab, do
grep -vP "^\t" abc.txt
-P turns on Perl-style regex (otherwise tab cannot be specified as \t). "^\t" matches lines beginning with a tab. -v inverts the selection.

For most cases though, using -E (extended regex) instead of -P works, and is better supported.