Monday, January 24, 2011

String Concatenation in Python

Build a list of strings, then join it


def method():
str_list = []
for num in xrange(loop_count):
str_list.append(`num`)
return ''.join(str_list)

This approach is commonly suggested as a very pythonic way to do string concatenation. First a list is built containing each of the component strings, then in a single join operation a string is constructed conatining all of the list elements appended together.



Write to a pseudo file


from cStringIO import StringIO
import timing, commands, os
from sys import argv
def method():
from cStringIO import StringIO
file_str = StringIO()
for num in xrange(loop_count):
file_str.write(`num`)

The cStringIO module provides a class called StringIO that works like a file,
but is stored as a string. Obviously it's easy to append to a file - you simply
write at the end of it and the same is true for this module. There is a similar
module called just StringIO, but that's implemented in python whereas cStringIO
is in C. It should be pretty speedy. Using this object we can build our string
one write at a time and then collect the result using the getvalue() call.

return file_str.getvalue()

downloading rpm packages without installing them

You need to install plugin called yum-downloadonly. This plugin adds a --downloadonly flag to yum so that yum will only download the packages and not install/update them. Following options supported by this plugin:

[a] --downloadonly : don't update, just download a rpm file
[b] --downloaddir=/path/to/dir : specifies an alternate directory to store packages such as /tmp


How do I install yum-downloadonly plugin?

Type the following command to install plugin, enter:
# yum install yum-downloadonly



After this plugin is installed on yum, you can use the following command to download any rpm package and store it to downloaddir location.


Download RPM Packages
yum reinstall libXtst --downloadonly --downloaddir=/tmp