lunes, 27 de julio de 2009

Get IP address of a host

If you need to get the IP address of a host, but you don't want to parse the output of ifconfig, you can use hostname:

$ hostname -i
192.168.1.160
$ _

viernes, 17 de julio de 2009

UnicodeEncodeError: 'ascii' codec can't encode character XXX

 Yet another text-format error in python (personal error, of course)...  while I was trying to store in file a joined list (through list comprehension), one or more of the characters of one the fields that are being joined generate the following 'friendly message':

Traceback (most recent call last):
  File "stations.py", line 62, in
  exit(main())
  File "stations.py", line 16, in main
  record.append(str(element.text))
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf1' in position 7: ordinal not in range(128)

 to avoid it, instead of trying to cast into a string the variable, you could use the repr() function... 

repr(object)
  Return a string containing a printable representation of an object.
  (http://docs.python.org/library/functions.html)

Example:

>>> caca = u'\u2603'
>>> print caca

>>> str(caca)
Traceback (most recent call last):
  File "", line 1, in
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2603' in position 0: ordinal not in range(128)
>>> repr(caca)
"u'\\u2603'"

solution from:
http://blog.codekills.net/archives/45-str...-yer-probably-doin-it-wrong..html

martes, 14 de julio de 2009

shp2pgsql UTF-8 enconding workaround

While trying to convert a shapefile and load it to a DB, some latin characters on the data were a problem and the parameter that shp2pgsql provides for the encoding did not work

shp2pgsql -W "UTF-8" ... :(

Then, a nice workaround is to use | with iconv:
shp2pgsql  file.shp  schema.table | iconv -f LATIN1 -t UTF-8 | psql

viernes, 10 de julio de 2009

Python broken pipe

This could be little weird but I have seen this, more than once. When you work in python , parsing the standard input, and for some reason you use a pipe at the end of you process to see the head or tail like:
python foo.py| head
and you get a Broken Pipe Error then the next code snippet could be useful.


import sys
for line in sys.stdin:
print line.strip()


Then run your program and you will get

$ yes | python pipe.py |head
y
y
y
y
y
Traceback (most recent call last):
File "pipe.py", line 5, in ?
print line
IOError: [Errno 32] Broken pipe


To avoid this error just use signal package:

import signal
import sys

signal.signal(signal.SIGPIPE, signal.SIG_DFL)

for line in sys.stdin:
print line.strip()



Enjoy