~
~
:wq

Showing posts with label python. Show all posts
Showing posts with label python. Show all posts

Saturday, 27 June 2015

Passing STDIN or positional arguments to python code enbedded in bash script (here-documents)

spanish version - all english posts

This is a short post about bash's here-documents and python embedded scripts. Very useful to write quick and dirty scripts.

The issue here is to demonstrate how to pass either positional arguments or stdin input (pipe) to python code inside a bash's here-document block of code

Proposal, write a bash script or function that accepts either pipe input or positional parameters and pass them to a python block of code within the bash script.

First approach: ever wonder how to pass bash positional args to inside python here document? Here is the code:

#! /bin/bash

[... bash stuff ...]

# our python block
python - $@ << EOF
import sys
print sys.argv[:]
EOF

[... more bash stuff ...]

this is how it works:

bash firstapproach.sh one two
['-', 'one', 'two']

Let's go ahead... What if you want to accept ether standard input or positional args? this is IMHO a good approach to the problem (using a function to make the code clearer):

#! /bin/bash

[... bash stuff ...]

# the function which passes to our python here-document either
# positional args or STDIN input
# pipe input is only used if no positional args are present:
myfunct () {
[[ $# > 0 ]] && ARGS=$@ || read ARGS
python - $ARGS << EOF
import sys
print sys.argv[:]
exit
EOF
}

[... more bash stuff ...]

And here is the resulting output of both the STDIN and the positional args:

~$ echo hola amigos | myfunct
['-', 'hola', 'amigos']

~$ myfunct hasta luego
['-', 'hasta', 'luego']

HTH

Friday, 26 June 2015

Pasar argumentos posicionales (o STDIN) del script bash a un bloque python en un here-document

english version - all spanish posts

Aquí va un post corto sobre scripts en bash con código incrustado de python en "here-documents". Muy útil para scriping rápido.

El asunto aquí es demostrar cómo pasar tanto argumentos posicionales como desde la entrada estandar a un bloque de código python incrustado en un here-document dentro de un script de bash

Propuesta: escribir un script o una función bash que acepte parámetros posicionales o STDIN y que se los pase al bloque de python dentro del here-document.

Aproximación inicial: ¿nunca has querido saber cómo pasar los argumentos posicionales del script de bash al bloque de python que tienes en tu script? Aquí va el código:

#! /bin/bash

[... código bash ...]

# Nuestro bloque python
python - $@ << EOF
import sys
print sys.argv[:]
EOF

[... más código bash ...]

Así funciona:

bash aproximacioninicial.sh one two
['-', 'one', 'two']

Vamos a avanzar un poco más... ¿Qué pasa si queremos aceptar también un pipe desde el STDIN? En mi «humilde» opinión esta sería una buena aproximación a la resolución del problema (utilizo una función para hacer el código más claro):

#! /bin/bash

[... código bash ...]

# la funciona que pasa a nuestro python tanto 
# argumentos posicionales como input del STDIN
# en este caso si no hay argumentos utilizamos el STDIN
myfunct () {
[[ $# > 0 ]] && ARGS=$@ || read ARGS
python - $ARGS << EOF
import sys
print sys.argv[:]
exit
EOF
}

[... mas código bash ...]

Y aquí está la salida resultante tanto de la STDIN como cuando usamos los argumentos posicionales:

~$ echo hola amigos | myfunct
['-', 'hola', 'amigos']

~$ myfunct hasta luego
['-', 'hasta', 'luego']

HTH

Sunday, 21 February 2010

Unicode and Python

spanish version - all english posts

This weekend I had in mind posting a few notes about how to correctly use unicode when programming with python. But after reviewing my bookmarks and rereading the magnificent post All About Python and Unicode I have come to the conclusion that publishing anything related to unicode would be light years behind of that wonderful tutorial.

I recommend anyone of you interested in the use of unicode that take a cup of coffee and read All About Python and Unicode.

Therefore, instead of the notes I was about to post, I will just list three references I personally use when I have to review unicode and python:

There are many more links, possibly better and newer, but with these three is sufficient to understand properly the use of unicode in python.

Unicode y python

english version - all spanish posts

Este fin de semana tenía en mente publicar unas notas sobre cómo usar correctamente unicode al programar con python, pero tras repasar los enlaces que tengo guardados al respecto y releer el magnífico post All About Python and Unicode he llegado a la conclusión de que cualquier cosa que publique quedaría a años luz de ese estupendo tutorial.

Recomiendo a cualquiera que tenga interés en el uso de unicode que coja una taza de café y le dedique un rato a All About Python and Unicode.

Por tanto, en lugar de las notas que había pensado poner, paso a listar tres enlaces que personalmente uso como referencia:

Hay muchos más enlaces, quizá mejores y más recientes, pero con estos tres es suficiente para entender correctamente el uso de unicode en python.

Saturday, 23 January 2010

Counting pages

spanish version - all english posts

We have an application that generates PDF reports from rst formated text files. One of the requirements that the applicaction should have is the numbering of pages in the format "Page X of Y". Unfortunaltely our application is an implemetation of rst2pdf 0.11 which doesn't have shuch feature (at least in the version we have). Although it wouldn't be too complex to implement it by modifying the code of python-docutils, this goes against my principles: Packages should be maintained by their developers at first instance, and by the distro packagers at second stage (in this case Ubuntu LTS 8.04). As an administrator I do not like altering this policy because then we must be aware of future security updates that may break things when our changes will be overriden.

I'm a bash guy, hence I always tend to prototype using the shell. So here is a quick way to implement a method to count the total pages of a PDF document w/o installing any specific tool.

Total PDF pages obtained by grep:

hmontoliu@blogspot:/tmp$ grep -c --binary-files=text '/Page\b' foo.pdf
818

Of course the package xpdf-utils includes the command "pdfinfo" which reports the number of pages in a document; but again, if you can avoid installing extra packages on a server much better.

The avobe command also applies to ps documents with minor modifications:

hmontoliu@blogspot:/tmp$ grep -c '%%Page' bar.ps
5

More information at "man grep" :-)

Implementing this simple grep in python as a call to the shell or doing a grep-like stuff through re or string.count('text') is trivial; for example:

In [1]: with open('/tmp/foo.pdf','rb') as f:
   ...:     f.read().count('/Page>')
   ...:
   ...: 

Out[1]: 818

Contando páginas

english version - all spanish posts

Tenemos una aplicación que genera informes en PDFs a partir de ficheros con formato rst. Uno de los requisitos que debía tener la aplicación es la numeración de páginas de tipo "página X de Y". Lamentablemente se trata de una implementación a partir de rst2pdf 0.11 que de momento no incorpora esa característica (al menos en la versión que tenemos). Aunque no sería demasiado complejo implementarla modificando el código de python-docutils esto va en contra de mis principios: Los paquetes los deben mantener primero sus desarrolladores y en segunda instancia la distribución de turno; en este caso Ubuntu LTS 8.04. Como administrador no me gusta alterar esta política pues luego hay que estar pendiente de qué se rompe o se deja de romper con las actualizaciones de seguridad.

Como las cabras que tiran al monte, yo siempre tiro a la shell para «prototipar». Así que aquí va un método rápido de implementar que permite contar el total de páginas de un PDF sin herramientas específicas.

Páginas de un documento PDF obtenidas con grep:

hmontoliu@blogspot:/tmp$ grep -c --binary-files=text '/Page\b' foo.pdf
818

Por supuesto el paquete xpdf-utils incluye el comando "pdfinfo" que informa del número de páginas de un documento; pero, nuevamente, si se puede evitar la instalación de paquetes extra en un servidor mucho mejor.

El anterior grep nos vale también para documentos PS con mínimas modificaciones:

hmontoliu@blogspot:/tmp$ grep -c '%%Page' bar.ps
5

Mas información en man grep :-)

Implementar este sencillo grep en python como llamada a la shell o haciendo un grep-like directamente con python mediante re o con un cadena.count('texto') es trivial; por ejemplo:

In [1]: with open('/tmp/foo.pdf','rb') as f:
   ...:     f.read().count('/Page>')
   ...:
   ...: 

Out[1]: 818