<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>Linux by Examples</title>
	
	<link>http://linux.byexamples.com</link>
	<description>We explain every GNU/Linux command by examples in this blog!</description>
	<pubDate>Sun, 31 Jan 2010 11:26:48 +0000</pubDate>
	<generator>http://wordpress.org/?v=abc</generator>
	<language>en</language>
			<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/LinuxByExamples" /><feedburner:info uri="linuxbyexamples" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com" /><feedburner:emailServiceId>LinuxByExamples</feedburner:emailServiceId><feedburner:feedburnerHostname>http://feedburner.google.com</feedburner:feedburnerHostname><item>
		<title>Install RPM with yum</title>
		<link>http://feedproxy.google.com/~r/LinuxByExamples/~3/9rgffPbigyY/</link>
		<comments>http://linux.byexamples.com/archives/521/install-rpm-with-yum/#comments</comments>
		<pubDate>Sun, 31 Jan 2010 11:26:48 +0000</pubDate>
		<dc:creator>mysurface</dc:creator>
		
		<category><![CDATA[yum]]></category>

		<guid isPermaLink="false">http://linux.byexamples.com/?p=521</guid>
		<description><![CDATA[I am a Linux user for couple of years, and I am using fedora for quite sometimes too. To install the packages that I need, first I will check them out at my repository using yum.
yum search something
p.s Replace &#8217;something&#8217; with your keywords.
If I manage to obtain the package list, I can install them like [...]]]></description>
			<content:encoded><![CDATA[<p>I am a Linux user for couple of years, and I am using fedora for quite sometimes too. To install the packages that I need, first I will check them out at my repository using yum.</p>
<pre><code>yum search something</code></pre>
<p><em>p.s Replace &#8217;something&#8217; with your keywords.</em></p>
<p>If I manage to obtain the package list, I can install them like this:</p>
<pre><code>yum install something</code></pre>
<p>But that is not always the case. Sometimes the packages I need is just not exist under my repository, I can only obtain the rpm files from the external site. By installing rpm file using rpm command introduces a problem. I have to resolves the dependencies of the particular rpm myself.</p>
<p>Then, I have to search more rpm files to resolve the dependencies.</p>
<p>But today, I realized that I could install rpm files using yum, and yum resolves the dependencies for me. The command line is quite straight forward too. Let say I wanna install &#8217;something.i586.rpm&#8217;, I can install it with yum like this:</p>
<pre><code>yum install something.i586.rpm</code></pre>
<p>Thanks to yum developers, it save a lots of my time.</p>
<div class="aizatto_related_posts"><span class="aizatto_related_posts_header" >Related Posts</span><br/><span class="aizatto_related_posts_title" ><a href="http://linux.byexamples.com/archives/156/installing-from-tarballs/" rel="bookmark" title="Permanent Link: Installing From Tarballs" >Installing From Tarballs</a></span><div class="aizatto_related_posts_excerpt">We usually download linux programs through package handling tools such as yum and apt-get. Download programs through pac...</div><p></p><span class="aizatto_related_posts_title" ><a href="http://linux.byexamples.com/archives/161/how-to-check-what-have-installed-in-debianubuntu/" rel="bookmark" title="Permanent Link: How to check what have installed in Debian/Ubuntu" >How to check what have installed in Debian/Ubuntu</a></span><div class="aizatto_related_posts_excerpt">To check what have install by listing all using dpkg is easy.
dpkg -l

To check whether a package is install also eas...</div><p></p><span class="aizatto_related_posts_title" ><a href="http://linux.byexamples.com/archives/82/run-multiple-commands-consequently/" rel="bookmark" title="Permanent Link: Run multiple commands consequently" >Run multiple commands consequently</a></span><div class="aizatto_related_posts_excerpt">By specified terminator ( ; ) like in C/C++ programming, you can run multiple commands consequently. We usually want to ...</div><p></p></div>
<p><a href="http://feedads.g.doubleclick.net/~a/a_fOkTnoJnuODN51Hdy8wT8GGt4/0/da"><img src="http://feedads.g.doubleclick.net/~a/a_fOkTnoJnuODN51Hdy8wT8GGt4/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/a_fOkTnoJnuODN51Hdy8wT8GGt4/1/da"><img src="http://feedads.g.doubleclick.net/~a/a_fOkTnoJnuODN51Hdy8wT8GGt4/1/di" border="0" ismap="true"></img></a></p><img src="http://feeds.feedburner.com/~r/LinuxByExamples/~4/9rgffPbigyY" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://linux.byexamples.com/archives/521/install-rpm-with-yum/feed/</wfw:commentRss>
		<feedburner:origLink>http://linux.byexamples.com/archives/521/install-rpm-with-yum/</feedburner:origLink></item>
		<item>
		<title>Split screen console terminal ~ Terminator</title>
		<link>http://feedproxy.google.com/~r/LinuxByExamples/~3/LqbRcEJGvoE/</link>
		<comments>http://linux.byexamples.com/archives/517/split-screen-console-terminal-terminator/#comments</comments>
		<pubDate>Sun, 03 Jan 2010 03:54:23 +0000</pubDate>
		<dc:creator>mysurface</dc:creator>
		
		<category><![CDATA[Misc]]></category>

		<category><![CDATA[terminator]]></category>

		<guid isPermaLink="false">http://linux.byexamples.com/?p=517</guid>
		<description><![CDATA[Sometimes, you may have many logs to trace at once, you may need to copy and paste text from files to files, and tabbed terminal is just not convenient enough.
So, you hope for a terminal that allows you to split your console screen into either horizontal or vertical flexibly. If you have such requirements like [...]]]></description>
			<content:encoded><![CDATA[<p>Sometimes, you may have many logs to trace at once, you may need to copy and paste text from files to files, and tabbed terminal is just not convenient enough.</p>
<p>So, you hope for a terminal that allows you to split your console screen into either horizontal or vertical flexibly. If you have such requirements like I do, then you are looking for console terminal software just like <a href="http://www.tenshu.net/terminator/">Terminator</a>.</p>
<p>Terminator implements those flexibility of arranging terminals based on Gnome terminal. It allows you to <strong>split</strong> your screen putting the terminals as a single view. You can <strong>switch</strong> the terminals by just drag and drops. You can still <strong>adjust</strong> the size of each terminals. The <strong>tabbed</strong> features remains, therefore you can still have multiple tabs and each tab you may have multiple terminals.</p>
<p>Terminator re-implements the <strong>shortcut</strong> keys capabilities, you can create and edit .config/terminator/config to define your shortcut keys there. Check out the manual page for more info.</p>
<pre><code>man terminator_config</code></pre>
<p>At last please check out this ridiculous screenshot:</p>
<p><a href="http://www.tenshu.net/wp-content/uploads/2008/02/terminator-mad.png"><img src="http://www.tenshu.net/wp-content/uploads/2008/02/terminator-mad.thumbnail.png" alt="" /></a></p>
<p>Have Fun!</p>
<div class="aizatto_related_posts"><span class="aizatto_related_posts_header" >Related Posts</span><br/><span class="aizatto_related_posts_title" ><a href="http://linux.byexamples.com/archives/27/split-windows-view-in-vim/" rel="bookmark" title="Permanent Link: split windows view in vim" >split windows view in vim</a></span><div class="aizatto_related_posts_excerpt">Sometimes you would likes to have split view. You can compare the codes at the same time on the same screen. So when swi...</div><p></p><span class="aizatto_related_posts_title" ><a href="http://linux.byexamples.com/archives/86/multiple-workspace-on-single-terminal-with-screen/" rel="bookmark" title="Permanent Link: multiple workspace on single terminal with screen" >multiple workspace on single terminal with screen</a></span><div class="aizatto_related_posts_excerpt">Screen is a useful tool, it allows you to have multiple workspace on a single terminal. Linux usually support 5 virtual ...</div><p></p><span class="aizatto_related_posts_title" ><a href="http://linux.byexamples.com/archives/49/clear-screen/" rel="bookmark" title="Permanent Link: clear screen" >clear screen</a></span><div class="aizatto_related_posts_excerpt">If you do clear screen by type
clear
Try to scroll ur mouse up, you will figure out that, your previous typed command ...</div><p></p></div>
<p><a href="http://feedads.g.doubleclick.net/~a/AYgM_qG4xekl264M8uq94SvNigM/0/da"><img src="http://feedads.g.doubleclick.net/~a/AYgM_qG4xekl264M8uq94SvNigM/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/AYgM_qG4xekl264M8uq94SvNigM/1/da"><img src="http://feedads.g.doubleclick.net/~a/AYgM_qG4xekl264M8uq94SvNigM/1/di" border="0" ismap="true"></img></a></p><img src="http://feeds.feedburner.com/~r/LinuxByExamples/~4/LqbRcEJGvoE" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://linux.byexamples.com/archives/517/split-screen-console-terminal-terminator/feed/</wfw:commentRss>
		<feedburner:origLink>http://linux.byexamples.com/archives/517/split-screen-console-terminal-terminator/</feedburner:origLink></item>
		<item>
		<title>Compile and execute 32 bits application in 64 bits operating system</title>
		<link>http://feedproxy.google.com/~r/LinuxByExamples/~3/04RiFMlJu1c/</link>
		<comments>http://linux.byexamples.com/archives/515/compile-and-execute-32-bits-application-in-64-bits-operating-system/#comments</comments>
		<pubDate>Thu, 01 Oct 2009 12:02:27 +0000</pubDate>
		<dc:creator>mysurface</dc:creator>
		
		<category><![CDATA[Developer]]></category>

		<category><![CDATA[Misc]]></category>

		<category><![CDATA[gcc]]></category>

		<guid isPermaLink="false">http://linux.byexamples.com/?p=515</guid>
		<description><![CDATA[The world is going towards 64 bits machines and operating system for personal computer, but there are still some libs and software only support 32 bits. Therefore in this transition period, there is a needs to support both 64 bits and 32 bits applications.
Lately I been using x86_64 Fedora Linux. There are requirements for me [...]]]></description>
			<content:encoded><![CDATA[<p>The world is going towards 64 bits machines and operating system for personal computer, but there are still some libs and software only support 32 bits. Therefore in this transition period, there is a needs to support both 64 bits and 32 bits applications.</p>
<p>Lately I been using x86_64 Fedora Linux. There are requirements for me execute some 32 bits binaries as well as compiling to produce 32 bits binaries. </p>
<p>First of all, I do not aware of any great different for me based on user experience while migrating from 32 bits to 64 bits Fedora. Maybe this is because the fedora repository is in the good shape, where everything that I had downloaded by using yum, will works perfectly.</p>
<p>Until one day I downloaded some legacy projects from the 3rd party website, that piece of software comes with 32 bits libs which needs 32 bits compilation. I started to realized that the binaries that I had compiled in my 64 bits environment is not working at 32 bits OS even though I am using the legacy version of gcc 3.4 compiler.</p>
<p>Fedora x86_64 allows you to run 32 bits software given that the dynamic libs is installed properly. I realized that my fedora does have two directories for lib, <strong>/lib</strong> and another one is <strong>/lib64</strong>. When I am searching for a particular lib using yum, let say libxml2, I realized that yum is actually returns me both 32 bits and 64 bits result.</p>
<pre><code>
yum search libxml2
...
libxml2.i386 : Library providing XML and HTML support
libxml2.x86_64 : Library providing XML and HTML support
...
</code></pre>
<p>By default if I execute &#8220;yum install libxml2&#8243;, yum will install the 64 bits one for me. In my case I want the 32 bits glibc, what I have to do is to specify the exact package name.</p>
<pre><code>yum install libxml2.i386</code></pre>
<p>After the installation, now I can run the 32 bits application that requires libxml2.</p>
<p><b>How about compiling 32 bits application in 64 bits operating system?</b></p>
<p>First of all, I need to make sure I had installed all the development packages of the 32 bits libs required. Let takes libxml2 as the example, I need to yum &#8216;libxml2-devel.i386&#8242;.</p>
<p>Next tell gcc that I am going to compile the codes into 32 bit binaries by specify the -m32 CFLAGS. Assume I wrote a simple hello.c.</p>
<pre><code>gcc -m32 -o hello{,.c} -lxml2</code></pre>
<p>Now I need to produce the binary that can be run under Red Hat es4. I know the default version of gcc for RHES4 is 3.4 which I need gcc34 in my fedora. ( I need to yum another package &#8216;compat-gcc-34.x86_64&#8242; for that) . With that now I can compile the codes at my x86_64 fedora to produce binary that can run at RHES4.</p>
<pre><code>gcc34 -m32 -o hello{,.c} -lxml2</code></pre>
<div class="aizatto_related_posts"><span class="aizatto_related_posts_header" >Related Posts</span><br/><span class="aizatto_related_posts_title" ><a href="http://linux.byexamples.com/archives/202/compile-c-and-c-source-code/" rel="bookmark" title="Permanent Link: compile c and c++ source code" >compile c and c++ source code</a></span><div class="aizatto_related_posts_excerpt">There are plenty of c and c++ compiler under unix based operating system, but the most famous one should be GNU gcc comp...</div><p></p><span class="aizatto_related_posts_title" ><a href="http://linux.byexamples.com/archives/317/sha-1-checksum/" rel="bookmark" title="Permanent Link: sha-1 checksum" >sha-1 checksum</a></span><div class="aizatto_related_posts_excerpt">What is sha-1 checksum? I heard about md5 checksum, did sha-1 makes any different?

Sha-1 is another algorithm that is...</div><p></p><span class="aizatto_related_posts_title" ><a href="http://linux.byexamples.com/archives/496/bit-shifting-can-be-done-in-python-just-like-in-c/" rel="bookmark" title="Permanent Link: Bit shifting can be done in python just like in c" >Bit shifting can be done in python just like in c</a></span><div class="aizatto_related_posts_excerpt">It was amazing to discover that I can do bit shifting in python just like in c, the syntax makes no different at all. Le...</div><p></p></div>
<p><a href="http://feedads.g.doubleclick.net/~a/Cctdyg-mVsQSzDcVarhhtKK4q1g/0/da"><img src="http://feedads.g.doubleclick.net/~a/Cctdyg-mVsQSzDcVarhhtKK4q1g/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/Cctdyg-mVsQSzDcVarhhtKK4q1g/1/da"><img src="http://feedads.g.doubleclick.net/~a/Cctdyg-mVsQSzDcVarhhtKK4q1g/1/di" border="0" ismap="true"></img></a></p><img src="http://feeds.feedburner.com/~r/LinuxByExamples/~4/04RiFMlJu1c" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://linux.byexamples.com/archives/515/compile-and-execute-32-bits-application-in-64-bits-operating-system/feed/</wfw:commentRss>
		<feedburner:origLink>http://linux.byexamples.com/archives/515/compile-and-execute-32-bits-application-in-64-bits-operating-system/</feedburner:origLink></item>
		<item>
		<title>How to mount a ssh server?</title>
		<link>http://feedproxy.google.com/~r/LinuxByExamples/~3/nztWNCL2GhQ/</link>
		<comments>http://linux.byexamples.com/archives/513/how-to-mount-a-ssh-server/#comments</comments>
		<pubDate>Fri, 18 Sep 2009 11:31:23 +0000</pubDate>
		<dc:creator>mysurface</dc:creator>
		
		<category><![CDATA[Admin]]></category>

		<category><![CDATA[sshfs]]></category>

		<guid isPermaLink="false">http://linux.byexamples.com/?p=513</guid>
		<description><![CDATA[After FUSE (Filesystem in Userspace) was invented, it opens up a lots of possibility to mount a remote filesystem on various protocol, such as FTP and SSH. FUSE is an API to implement a fully functional filesystem in a userspace program. 
I had wrote a post shares the idea how we can mount a ftp [...]]]></description>
			<content:encoded><![CDATA[<p>After <a href="http://fuse.sourceforge.net/">FUSE</a> (Filesystem in Userspace) was invented, it opens up a lots of possibility to mount a remote filesystem on various protocol, such as FTP and SSH. FUSE is an API to implement a fully functional filesystem in a userspace program. </p>
<p>I had wrote a post shares the idea how we can <a href="http://linux.byexamples.com/archives/344/mounting-ftp-host-to-local-directory-on-top-of-fuse/">mount a ftp host</a>, the same way we can mount a ssh point using sshfs. </p>
<p>With sshfs, we can mount a remote directory through ssh, the command line works like this:</p>
<pre><code>
sshfs <strong>user-name</strong>@<strong>host-ip</strong>:<strong>remote-dir</strong> <strong>mount-point</strong>
</code></pre>
<p><strong>Mount-point</strong> is simply a directory which we can trigger mkdir to create one. If we want to mount the user&#8217;s home directory at the remote server, we can leave the <strong>remote-dir</strong> as blank. For examples I want to connect to 192.168.1.1, I can do this: ( Assume I created a folder call ssh_mount )</p>
<pre><code>sshfs surface@192.168.1.1: ssh_mount</code></pre>
<p>As simple as that, we had done mounting the ssh server. But bear in mind, it is not the same like you ssh to the server. We are just mounting a remote filesystem, we are still working under the local system environment.</p>
<div class="aizatto_related_posts"><span class="aizatto_related_posts_header" >Related Posts</span><br/><span class="aizatto_related_posts_title" ><a href="http://linux.byexamples.com/archives/75/attach-an-external-devices/" rel="bookmark" title="Permanent Link: Attach an external devices" >Attach an external devices</a></span><div class="aizatto_related_posts_excerpt">When you plug in the USB thumb drive into your pc, in a flash OSes will help you mount the device. But what happen if it...</div><p></p><span class="aizatto_related_posts_title" ><a href="http://linux.byexamples.com/archives/100/enable-a-user-to-gain-write-permission-when-mounting/" rel="bookmark" title="Permanent Link: Enable a user to gain write permission when mounting" >Enable a user to gain write permission when mounting</a></span><div class="aizatto_related_posts_excerpt">We need to perform mounting with root privilege, but after a simple mounting, we need to be root in order to write to th...</div><p></p><span class="aizatto_related_posts_title" ><a href="http://linux.byexamples.com/archives/101/mount-a-samba-point/" rel="bookmark" title="Permanent Link: mount a samba point" >mount a samba point</a></span><div class="aizatto_related_posts_excerpt">You may heard about smbmount, smbfs or cifs. Yes if you are looking for how to mount a point to access to other machine ...</div><p></p></div>
<p><a href="http://feedads.g.doubleclick.net/~a/wv5PGlWydkvaxP7A117iD24HVY8/0/da"><img src="http://feedads.g.doubleclick.net/~a/wv5PGlWydkvaxP7A117iD24HVY8/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/wv5PGlWydkvaxP7A117iD24HVY8/1/da"><img src="http://feedads.g.doubleclick.net/~a/wv5PGlWydkvaxP7A117iD24HVY8/1/di" border="0" ismap="true"></img></a></p><img src="http://feeds.feedburner.com/~r/LinuxByExamples/~4/nztWNCL2GhQ" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://linux.byexamples.com/archives/513/how-to-mount-a-ssh-server/feed/</wfw:commentRss>
		<feedburner:origLink>http://linux.byexamples.com/archives/513/how-to-mount-a-ssh-server/</feedburner:origLink></item>
		<item>
		<title>Serialize INI configuration to python dictionary</title>
		<link>http://feedproxy.google.com/~r/LinuxByExamples/~3/wnq58RR5HpQ/</link>
		<comments>http://linux.byexamples.com/archives/511/serialize-ini-configuration-to-python-dictionary/#comments</comments>
		<pubDate>Sun, 30 Aug 2009 05:17:33 +0000</pubDate>
		<dc:creator>mysurface</dc:creator>
		
		<category><![CDATA[Developer]]></category>

		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://linux.byexamples.com/?p=511</guid>
		<description><![CDATA[A  lots of configuration file is in the format of INI, if we manage to serialize INI configuration to python dictionary, we can write python scripts to analyse and generate back to INI files.
Below is the sample of INI configuration: config.ini

#
# GENERAL section contains generic configuration
#
[GENERAL]
IP=192.168.1.4
Port=2143

#
# LOG section contains logging settings
#
[LOG]
LogLevel=5
LogPath=/var/log
LogType=Info Trace Error Debug

I [...]]]></description>
			<content:encoded><![CDATA[<p>A  lots of configuration file is in the format of INI, if we manage to serialize INI configuration to python dictionary, we can write python scripts to analyse and generate back to INI files.</p>
<p>Below is the sample of INI configuration: <strong>config.ini</strong></p>
<pre><code>
#
# GENERAL section contains generic configuration
#
[GENERAL]
IP=192.168.1.4
Port=2143

#
# LOG section contains logging settings
#
[LOG]
LogLevel=5
LogPath=/var/log
LogType=Info Trace Error Debug
</code></pre>
<p>I created few python function use to serialize the INI configuration into dictionary. But there are some assumption to make. Assume that the comment of INI is start with char &#8216;#&#8217;. python dictionary do not takes in comments, because comment is not configuration. But what if after I change the configurations in dictionary and want to serialize back to INI file with the original comments stayed in as well? Yes you can remain the comments with the set of python functions I wrote.</p>
<p>Lets look at what function I have.<br />
<strong>grep (str_list,pattern,neg=False):</strong> is my internal function to filter element in string list (first param).</p>
<p><strong>ParseConfig (name=None):</strong> put the INI config filename as param, dictionary object will be returned.</p>
<p><strong>ConfigTemplate (name=None):</strong> The construct the INI structure in another dictionary, storing the Section Name as well as your comments. </p>
<p><strong>ConfigWrite (template=[],config=[],filename=&#8221;"):</strong> This function is to serialize back the python dictionary back to INI file. First param takes in the template dictionary object, second takes in configuration dictionary object.</p>
<p>Lets us look at all functions definition as well as the examples: ParseConfig.py</p>
<pre><code>
#/usr/bin/env python
import sys,os,datetime,time,re,string
from StringIO import StringIO

GREP_NEGATIVE=True

def grep (str_list,pattern,neg=False):
    """grep() will return list of match case.
Param: str_list - must be a list of string, each element in list is a new line
                  can use .split('\n') to obtain list from mutiple line of string
Param: pattern - re pattern can be composed by re.compile()"""
    sres=[] #empty list
    for s in str_list:
        r=re.search(pattern,s,re.VERBOSE)
        if r and neg==False:
            sres.append(s)
        elif (not r) and neg==True:
            sres.append(s)

    return sres

def ParseConfig (name=None):
    global GREP_NEGATIVE
    """ Parsing config file to this function, will serialized to dictionary
@name  = filename
@return = dictionary"""
    configdict={}
    loglist=[]

    while True:
        try:
            f = open(name,"r")
        except IOError:
            print "Err ",name,"not exist"
            return None
            pass
        else:
            break

    try:
        for line in f:
            #strip all the whitespaces and write all lines to list.
            loglist.append(line.strip(string.whitespace))
    finally:
        f.close()

    # filter out the comment
    loglist=grep(loglist,"^\#",GREP_NEGATIVE)

    # make a dictionary
    xL=[] #current L
    itemdict={}
    for item in loglist:
        L=grep([item],"^\[.*\]$") # section
        if L:
            xL=[L[0].lstrip("[").rstrip("]")]
            itemdict={}
            #print xL
        else: # items?
            if len(xL)>0:
               if item:
                    #split index and values.
                    iL=item.split("=")
                    #replace all '\t' to " " in values
                    iL[1]=string.replace(iL[1],"\t"," ")
                    # split the values into list
                    iiL=iL[1].strip(string.whitespace).split(" ")
                    real_list=[]
                    for item in iiL:
                        # read each value in the list, if got something append to the real_list
                        if len(item.strip(string.whitespace)) is not 0:
                            real_list.append(item.strip(string.whitespace))
                    # create another dict into the section
                    itemdict[iL[0].strip(string.whitespace)]=real_list
                    configdict[xL[0]]=itemdict
    return configdict
pass

def ConfigTemplate (name=None):
    try:
        f=open(name,"r")
    except IOError:
        return None

    loglist=[]
    try:
        for line in f:
            #strip all the whitespaces and write all lines to list.
            theline = line.strip(string.whitespace)
            loglist.append(theline)
    finally:
        f.close()

    loglist=grep(loglist,"^\#|^\[")
    if len(loglist) is 0:
        loglist = None
    return loglist

def ConfigWrite (template=[],config=[],filename=""):
    global DebugDupConfigWrite

    if len(template) is 0 or len(config) is 0 or filename is "":
        return False

    try:
        f = open(filename,"w")
        for line in template:
            r=re.search("^\#",line,re.VERBOSE)
            if r:
                f.write(line + "\n")
            j=re.search("^\[",line,re.VERBOSE)
            if j:
                f.write(line + "\n")
                # get all section line up
                section_name = line.strip(string.whitespace).lstrip("[").rstrip("]")
                if config.has_key(section_name):
                    sec_dict = config[section_name]
                    #
                    element_list=[]
                    for element in sec_dict:
                        element_list.append(element)
                    element_list.sort()
                    for element in element_list:
                        # index = values....
                        #print element, sec_dict[element]
                        f.write(element + " = " + "\t".join(sec_dict[element]) + "\n")
                    f.write("\n")
                else:
                    pass
                    #f.write("CAN'T FIND THE ELEMENTS in section[%s]! DATA CORRUPTED.\n" % section_name)
                pass # end if j

            pass # end for line
        f.close()
        return True

    except:
        return False

# sample calling
myDict = ParseConfig ("config.ini")
template = ConfigTemplate ("config.ini")
ConfigWrite(template,myDict,"test.ini")

print "COMPLETE DICTIONARY"
print myDict

print "ALL TAGS"
for c in myDict:
    print " ",c

print ""
print "ALL ITEM IN 'GENERAL'"
for d in myDict["GENERAL"]:
    print " ",d

print ""
print "ALL ITEM IN 'LOG'"
for d in myDict["LOG"]:
    print " ",d

print ""
print "DIRECT ACCESS 'LOG's LOGTYPE'"
print myDict["LOG"]["LogType"]

print "SO, YOU CAN SEE THAT IS THE LIST, IT ITERATE the LIST"
for e in myDict["LOG"]["LogType"]:
    print " ",e

print "DIRECT ACCESS 'LOG's LOGTYPE 2nd value'"
print "second value is ",myDict["LOG"]["LogType"][1]
</code></pre>
<p>I hope my example is straight forward for you to understand how to use it, wish you enjoy python scripting :)</p>
<div class="aizatto_related_posts"><span class="aizatto_related_posts_header" >Related Posts</span><br/><span class="aizatto_related_posts_title" ><a href="http://linux.byexamples.com/archives/410/python-vs-lua-data-structure/" rel="bookmark" title="Permanent Link: Python vs Lua, data structure" >Python vs Lua, data structure</a></span><div class="aizatto_related_posts_excerpt">In python, we have various type of data structure, such as list, set, tuple, dictionary etc, but in Lua, we only have ta...</div><p></p><span class="aizatto_related_posts_title" ><a href="http://linux.byexamples.com/archives/350/python-careful-with-equal-sign/" rel="bookmark" title="Permanent Link: Python: Careful with equal sign" >Python: Careful with equal sign</a></span><div class="aizatto_related_posts_excerpt">To store data, object reference to a variable is very easy in python. For example, to assign an integer 5 to a
a=5

S...</div><p></p><span class="aizatto_related_posts_title" ><a href="http://linux.byexamples.com/archives/365/python-convey-the-exception-traceback-into-log-file/" rel="bookmark" title="Permanent Link: python: convey the exception traceback into log file" >python: convey the exception traceback into log file</a></span><div class="aizatto_related_posts_excerpt">Python is the interpreter language, you do not need to compile your code, and also you have no ways to check for your sy...</div><p></p></div>
<p><a href="http://feedads.g.doubleclick.net/~a/9nn5GIyBkpyWdzww8wwb8PGJhMI/0/da"><img src="http://feedads.g.doubleclick.net/~a/9nn5GIyBkpyWdzww8wwb8PGJhMI/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/9nn5GIyBkpyWdzww8wwb8PGJhMI/1/da"><img src="http://feedads.g.doubleclick.net/~a/9nn5GIyBkpyWdzww8wwb8PGJhMI/1/di" border="0" ismap="true"></img></a></p><img src="http://feeds.feedburner.com/~r/LinuxByExamples/~4/wnq58RR5HpQ" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://linux.byexamples.com/archives/511/serialize-ini-configuration-to-python-dictionary/feed/</wfw:commentRss>
		<feedburner:origLink>http://linux.byexamples.com/archives/511/serialize-ini-configuration-to-python-dictionary/</feedburner:origLink></item>
		<item>
		<title>Does scons outperforms autoconf and makefiles?</title>
		<link>http://feedproxy.google.com/~r/LinuxByExamples/~3/b67g0V5Q3vU/</link>
		<comments>http://linux.byexamples.com/archives/508/does-scons-outperforms-autoconf-and-makefiles/#comments</comments>
		<pubDate>Thu, 28 May 2009 15:59:26 +0000</pubDate>
		<dc:creator>mysurface</dc:creator>
		
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://linux.byexamples.com/?p=508</guid>
		<description><![CDATA[SCons is a software construction tool (build tool, or make tool) implemented in Python, that uses Python scripts as &#8220;configuration files&#8221; for software builds. Based on the design that won the Software Carpentry build tool competition, SCons solves a number of problems associated with other build tools, especially including the classic and ubiquitous Make itself.
In [...]]]></description>
			<content:encoded><![CDATA[<blockquote><p>SCons is a software construction tool (build tool, or make tool) implemented in Python, that uses Python scripts as &#8220;configuration files&#8221; for software builds. Based on the design that won the Software Carpentry build tool competition, SCons solves a number of problems associated with other build tools, especially including the classic and ubiquitous Make itself.</p>
<p>In its evolution, SCons will be more general than a make replacement, it will be a Gnu Build System replacement. The Gnu Build System (GBS) is also known as the set of Autotools (autoconf, automake, autoheader, etc&#8230;).</p>
<p>Quote From <a href="http://www.scons.org/wiki/TheBigPicture">http://www.scons.org/wiki/TheBigPicture</a></p></blockquote>
<p>So scons is just a makefile replacement? Which claims to be simple and feature rich? Let me construct a simple but sufficient scons configuration file (SConstruct), and show you how you can compile your c++ projects. Then you make the judgement whether to go for it or not.</p>
<pre><code>
#filename: SConstruct
env = Environment(
CXX = 'g++34',
CCFLAGS = ['-g','-O3','-Wall','-DPOSIX_C_SOURCE=199506L','-D_REENTRANT','-DLINT_ARGS','-DLINUXOS'],
LIBS = ['pthread', 'c','nsl','rt' ,'lbestd'],
LIBPATH = ['lib'],
CPPPATH = ['.','lib/inc'],
LINKFLAGS = ['-mt']
)

env.Program(
'bin/msgQ',
['Main.cc', 'MainState.cc','MainFunc.cc',
'MyLog.cc','MyQueue.cc','MyTcp.cc',
'TcpSvr.cc']
)
</code></pre>
<p>To compile the source codes, simply do this:</p>
<pre><code>scons</code></pre>
<p>To clear the objects and binaries, simply do this:</p>
<pre><code>scons -c</code></pre>
<p>Let me briefly explain the items in the SConstruct file.</p>
<p>By default, scons does define a simple compilation environment for you, if you write helloworld.cc, you just need to write a line in SConstruct.</p>
<pre><code>Program('helloworld.cc')</code></pre>
<p>But the case above, I overwrite some environment variable&#8217;s value for my needs to build a complex application.</p>
<p>CXX is the variable defines you c++ compiler. My case, I change it to g++34.</p>
<p>You can check the default value by just insert a python print statement in your SConstruct file.</p>
<pre><code>env = Environment()
print "CXX = ", env['CXX']</code></pre>
<p>CCFLAGS defines compilation flags.<br />
LIBS defines library to link.<br />
LIBPATH defines additional library paths besides the system default.<br />
CPPPATH defines include file paths.<br />
LINKFLAGS defines compiler linker flags</p>
<p>After constructed the environment, just compile your binary by calling <strong>Program</strong> function.</p>
<p>scons have more features compiles java codes too and importantly it is cross platform. To know more? Check out the scons <a href="http://www.scons.org/doc/production/HTML/scons-man.html">man pages</a> ans well as <a href="http://www.scons.org/doc/production/HTML/scons-user.html">user manual</a>.</p>
<div class="aizatto_related_posts"><span class="aizatto_related_posts_header" >Related Posts</span><br/><span class="aizatto_related_posts_title" ><a href="http://linux.byexamples.com/archives/156/installing-from-tarballs/" rel="bookmark" title="Permanent Link: Installing From Tarballs" >Installing From Tarballs</a></span><div class="aizatto_related_posts_excerpt">We usually download linux programs through package handling tools such as yum and apt-get. Download programs through pac...</div><p></p><span class="aizatto_related_posts_title" ><a href="http://linux.byexamples.com/archives/345/pcregrep-grep-based-on-perl-compatible-regular-expressions/" rel="bookmark" title="Permanent Link: pcregrep, grep based on perl compatible regular expressions" >pcregrep, grep based on perl compatible regular expressions</a></span><div class="aizatto_related_posts_excerpt">grep supposedly support perl regex by specified -P option, but somehow my grep do not support that, it complains this wh...</div><p></p><span class="aizatto_related_posts_title" ><a href="http://linux.byexamples.com/archives/328/compile-fluxbox-under-ubuntu/" rel="bookmark" title="Permanent Link: Compile Fluxbox under Ubuntu" >Compile Fluxbox under Ubuntu</a></span><div class="aizatto_related_posts_excerpt">I make a fresh install of kubuntu and apt-get Fluxbox from Ubuntu repository yesterday and tried to login to Fluxbox. Fi...</div><p></p></div>
<p><a href="http://feedads.g.doubleclick.net/~a/Mk4CtY3gwQaib68sxwFDqL5wKhM/0/da"><img src="http://feedads.g.doubleclick.net/~a/Mk4CtY3gwQaib68sxwFDqL5wKhM/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/Mk4CtY3gwQaib68sxwFDqL5wKhM/1/da"><img src="http://feedads.g.doubleclick.net/~a/Mk4CtY3gwQaib68sxwFDqL5wKhM/1/di" border="0" ismap="true"></img></a></p><img src="http://feeds.feedburner.com/~r/LinuxByExamples/~4/b67g0V5Q3vU" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://linux.byexamples.com/archives/508/does-scons-outperforms-autoconf-and-makefiles/feed/</wfw:commentRss>
		<feedburner:origLink>http://linux.byexamples.com/archives/508/does-scons-outperforms-autoconf-and-makefiles/</feedburner:origLink></item>
		<item>
		<title>python: simple http server for file sharing</title>
		<link>http://feedproxy.google.com/~r/LinuxByExamples/~3/N_57IDAvqX4/</link>
		<comments>http://linux.byexamples.com/archives/506/python-simple-http-server-for-file-sharing/#comments</comments>
		<pubDate>Fri, 15 May 2009 00:39:40 +0000</pubDate>
		<dc:creator>mysurface</dc:creator>
		
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://linux.byexamples.com/?p=506</guid>
		<description><![CDATA[You do not need to setup apache server just to hosting your file for sharing. If you have python 2.5 and above, you can do this at the targeted directory to share.
python -m SimpleHTTPServer 9914
9914 is the port number I choose to host my web, assume my IP is 192.168.1.1, in firefox you can ask [...]]]></description>
			<content:encoded><![CDATA[<p>You do not need to setup apache server just to hosting your file for sharing. If you have python 2.5 and above, you can do this at the targeted directory to share.</p>
<pre><code>python -m SimpleHTTPServer 9914</code></pre>
<p>9914 is the port number I choose to host my web, assume my IP is 192.168.1.1, in firefox you can ask your friend to access this url: <a href="http://192.168.1.1:9914">http://192.168.1.1:9914</a>.</p>
<p>It is easy isn&#8217;t it? You do NOT even need to run it as root, just run it as normal user but make sure your firewall allow the chosen port number.</p>
<div class="aizatto_related_posts"><span class="aizatto_related_posts_header" >Related Posts</span><br/><span class="aizatto_related_posts_title" ><a href="http://linux.byexamples.com/archives/343/python-handle-string-from-pipelines-and-list-of-param/" rel="bookmark" title="Permanent Link: python: handle string from pipelines and list of param" >python: handle string from pipelines and list of param</a></span><div class="aizatto_related_posts_excerpt">While I was searching ways to implement pipeline input for my python apps, I read an article from linuxjournal.com that ...</div><p></p><span class="aizatto_related_posts_title" ><a href="http://linux.byexamples.com/archives/494/how-can-i-avoid-running-a-python-script-multiple-times-implement-file-locking/" rel="bookmark" title="Permanent Link: How can I avoid running a python script multiple times? Implement file locking." >How can I avoid running a python script multiple times? Implement file locking.</a></span><div class="aizatto_related_posts_excerpt">Sometimes we just need a single instance of the python script to run at a time. Meaning, the python script itself should...</div><p></p><span class="aizatto_related_posts_title" ><a href="http://linux.byexamples.com/archives/77/redirect-stderr-to-stdout/" rel="bookmark" title="Permanent Link: Redirect stderr to stdout" >Redirect stderr to stdout</a></span><div class="aizatto_related_posts_excerpt">Very simple, just remember:

	1 = stdout
	2 = stderr

In python, its unittest module loves to dump test results to ...</div><p></p></div>
<p><a href="http://feedads.g.doubleclick.net/~a/pkUPPrAgG6v62PCIDflkGndUJIo/0/da"><img src="http://feedads.g.doubleclick.net/~a/pkUPPrAgG6v62PCIDflkGndUJIo/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/pkUPPrAgG6v62PCIDflkGndUJIo/1/da"><img src="http://feedads.g.doubleclick.net/~a/pkUPPrAgG6v62PCIDflkGndUJIo/1/di" border="0" ismap="true"></img></a></p><img src="http://feeds.feedburner.com/~r/LinuxByExamples/~4/N_57IDAvqX4" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://linux.byexamples.com/archives/506/python-simple-http-server-for-file-sharing/feed/</wfw:commentRss>
		<feedburner:origLink>http://linux.byexamples.com/archives/506/python-simple-http-server-for-file-sharing/</feedburner:origLink></item>
		<item>
		<title>sometimes, grep alone is enough to do the task</title>
		<link>http://feedproxy.google.com/~r/LinuxByExamples/~3/_dXZTaK2-X0/</link>
		<comments>http://linux.byexamples.com/archives/503/sometimes-grep-alone-is-enough-to-do-the-task/#comments</comments>
		<pubDate>Tue, 14 Apr 2009 10:47:39 +0000</pubDate>
		<dc:creator>mysurface</dc:creator>
		
		<category><![CDATA[Text Manipulation]]></category>

		<category><![CDATA[grep]]></category>

		<category><![CDATA[scripting]]></category>

		<guid isPermaLink="false">http://linux.byexamples.com/?p=503</guid>
		<description><![CDATA[One thing that makes UNIXes command line so powerful is because of pipelines. Pipelines is a set of processes chained by their standard streams, so that the output of each process (stdout) feeds directly as input (stdin) of the next one. Simple words, pipelines pass the outcomes of a particular command as input to another [...]]]></description>
			<content:encoded><![CDATA[<p>One thing that makes UNIXes command line so powerful is because of pipelines. Pipelines is a set of processes chained by their standard streams, so that the output of each process (stdout) feeds directly as input (stdin) of the next one. Simple words, pipelines pass the outcomes of a particular command as input to another command, and these chained allows you to do a command line combo!</p>
<p>A complex combo, I have constructed one last time in post <a href="http://linux.byexamples.com/archives/332/what-is-your-10-common-linux-commands/">what is your 10 common linux commands?</a></p>
<pre><code>
history | awk '{CMD[$2]++;count++;}END { for (a in CMD)print CMD[a] " " CMD[a]/count*100 "% " a;}' |  \
grep -v "./" | \
column -c3 -s " " -t | \
sort -nr | nl |  head -n10
</pre>
<p></code></p>
<p>But sometimes we tend to misuse them, I found someone likes to do this:</p>
<pre><code>cat foobar.txt | grep "barfoo"</code></pre>
<p>Actually grep alone is enough to do the search, we do not need cat or meow for that. As I show him this:</p>
<pre><code>grep "barfoo" foobar.txt</code></pre>
<p>Another example is list the names of all files under a given directory that match a particular string. Let say I wanna obtain a list of files that have string &#8220;foobar&#8221;.</p>
<pre><code>find /opt/src/kmess -type f | xargs grep -l "foobar"</code></pre>
<p>Hey! find is cool but grep alone is enough to do the job.</p>
<pre><code>grep -lr "foobar" /opt/src/kmess</code></pre>
<p>Try to go through the grep manual, you will find out that grep is more powerful than what you expect.</p>
<div class="aizatto_related_posts"><span class="aizatto_related_posts_header" >Related Posts</span><br/><span class="aizatto_related_posts_title" ><a href="http://linux.byexamples.com/archives/257/sort-grep-c-results/" rel="bookmark" title="Permanent Link: Sort grep -c results" >Sort grep -c results</a></span><div class="aizatto_related_posts_excerpt">grep -c "TODO:" *.c

foo.c:1
bar.c:0
spam.c:44
egg.c:32
matrix.c:0
grep -c displays the total count of matching l...</div><p></p><span class="aizatto_related_posts_title" ><a href="http://linux.byexamples.com/archives/142/matching-whole-word-in-grep/" rel="bookmark" title="Permanent Link: Matching Whole Word in Grep" >Matching Whole Word in Grep</a></span><div class="aizatto_related_posts_excerpt">Is "grep" capable to match a whole word? The answer of cause is yes!!
grep -w "keyword" filename
this will only displa...</div><p></p><span class="aizatto_related_posts_title" ><a href="http://linux.byexamples.com/archives/140/exclusive-grep/" rel="bookmark" title="Permanent Link: Exclusive Grep" >Exclusive Grep</a></span><div class="aizatto_related_posts_excerpt">When you have 'grep' some keyword:
grep "keyword" filename
tons of lines and dozen of  words you don't want may show o...</div><p></p></div>
<p><a href="http://feedads.g.doubleclick.net/~a/rfR1ruUvSS_21vCJABqYV0BXrNk/0/da"><img src="http://feedads.g.doubleclick.net/~a/rfR1ruUvSS_21vCJABqYV0BXrNk/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/rfR1ruUvSS_21vCJABqYV0BXrNk/1/da"><img src="http://feedads.g.doubleclick.net/~a/rfR1ruUvSS_21vCJABqYV0BXrNk/1/di" border="0" ismap="true"></img></a></p><img src="http://feeds.feedburner.com/~r/LinuxByExamples/~4/_dXZTaK2-X0" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://linux.byexamples.com/archives/503/sometimes-grep-alone-is-enough-to-do-the-task/feed/</wfw:commentRss>
		<feedburner:origLink>http://linux.byexamples.com/archives/503/sometimes-grep-alone-is-enough-to-do-the-task/</feedburner:origLink></item>
		<item>
		<title>Bit shifting can be done in python just like in c</title>
		<link>http://feedproxy.google.com/~r/LinuxByExamples/~3/t-1ZP-r38GI/</link>
		<comments>http://linux.byexamples.com/archives/496/bit-shifting-can-be-done-in-python-just-like-in-c/#comments</comments>
		<pubDate>Wed, 01 Apr 2009 08:31:36 +0000</pubDate>
		<dc:creator>mysurface</dc:creator>
		
		<category><![CDATA[Developer]]></category>

		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://linux.byexamples.com/?p=496</guid>
		<description><![CDATA[It was amazing to discover that I can do bit shifting in python just like in c, the syntax makes no different at all. Let us look at how easy I can do a bit shifting. I write an example loop by shifting the bit leftwards.

for i in range(0,10):
    print "0x0001 &#60;&#60; [...]]]></description>
			<content:encoded><![CDATA[<p>It was amazing to discover that I can do bit shifting in python just like in c, the syntax makes no different at all. Let us look at how easy I can do a bit shifting. I write an example loop by shifting the bit leftwards.</p>
<pre><code>
for i in range(0,10):
    print "0x0001 &lt;&lt; %d = 0x%04X" % ( i , 0x1 &lt;&lt; i)
</code></pre>
<p>The result is</p>
<pre><code>
0x0001 &lt;&lt; 0 = 0x0001
0x0001 &lt;&lt; 1 = 0x0002
0x0001 &lt;&lt; 2 = 0x0004
0x0001 &lt;&lt; 3 = 0x0008
0x0001 &lt;&lt; 4 = 0x0010
0x0001 &lt;&lt; 5 = 0x0020
0x0001 &lt;&lt; 6 = 0x0040
0x0001 &lt;&lt; 7 = 0x0080
0x0001 &lt;&lt; 8 = 0x0100
0x0001 &lt;&lt; 9 = 0x0200
</code></pre>
<p>The important part in the example is this :</p>
<pre><code>0x1 &lt;&lt; i</code></pre>
<p>Let say I wanna shift the bits of a value rightwards 3 times, I will do this:</p>
<pre><code>value = 102
print value &gt;&gt; 3</code></pre>
<p>The result will be 12. </p>
<p>To know more about what is bit shifting, check out <a href="http://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts">wikipedia</a>.</p>
<p>Have Fun!</p>
<div class="aizatto_related_posts"><span class="aizatto_related_posts_header" >Related Posts</span><br/><span class="aizatto_related_posts_title" ><a href="http://linux.byexamples.com/archives/365/python-convey-the-exception-traceback-into-log-file/" rel="bookmark" title="Permanent Link: python: convey the exception traceback into log file" >python: convey the exception traceback into log file</a></span><div class="aizatto_related_posts_excerpt">Python is the interpreter language, you do not need to compile your code, and also you have no ways to check for your sy...</div><p></p><span class="aizatto_related_posts_title" ><a href="http://linux.byexamples.com/archives/410/python-vs-lua-data-structure/" rel="bookmark" title="Permanent Link: Python vs Lua, data structure" >Python vs Lua, data structure</a></span><div class="aizatto_related_posts_excerpt">In python, we have various type of data structure, such as list, set, tuple, dictionary etc, but in Lua, we only have ta...</div><p></p><span class="aizatto_related_posts_title" ><a href="http://linux.byexamples.com/archives/343/python-handle-string-from-pipelines-and-list-of-param/" rel="bookmark" title="Permanent Link: python: handle string from pipelines and list of param" >python: handle string from pipelines and list of param</a></span><div class="aizatto_related_posts_excerpt">While I was searching ways to implement pipeline input for my python apps, I read an article from linuxjournal.com that ...</div><p></p></div>
<p><a href="http://feedads.g.doubleclick.net/~a/1iBMrHNdQa2wXwFnMVRLcezmzw8/0/da"><img src="http://feedads.g.doubleclick.net/~a/1iBMrHNdQa2wXwFnMVRLcezmzw8/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/1iBMrHNdQa2wXwFnMVRLcezmzw8/1/da"><img src="http://feedads.g.doubleclick.net/~a/1iBMrHNdQa2wXwFnMVRLcezmzw8/1/di" border="0" ismap="true"></img></a></p><img src="http://feeds.feedburner.com/~r/LinuxByExamples/~4/t-1ZP-r38GI" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://linux.byexamples.com/archives/496/bit-shifting-can-be-done-in-python-just-like-in-c/feed/</wfw:commentRss>
		<feedburner:origLink>http://linux.byexamples.com/archives/496/bit-shifting-can-be-done-in-python-just-like-in-c/</feedburner:origLink></item>
		<item>
		<title>How can I avoid running a python script multiple times? Implement file locking.</title>
		<link>http://feedproxy.google.com/~r/LinuxByExamples/~3/SYPKk8Rri3c/</link>
		<comments>http://linux.byexamples.com/archives/494/how-can-i-avoid-running-a-python-script-multiple-times-implement-file-locking/#comments</comments>
		<pubDate>Thu, 12 Mar 2009 16:07:07 +0000</pubDate>
		<dc:creator>mysurface</dc:creator>
		
		<category><![CDATA[Developer]]></category>

		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://linux.byexamples.com/?p=494</guid>
		<description><![CDATA[Sometimes we just need a single instance of the python script to run at a time. Meaning, the python script itself should detects whether any instances of himself are still running and act accordingly.
Well, how to do it?
The idea is simple, the first instance of the python script will open a file, and lock it. [...]]]></description>
			<content:encoded><![CDATA[<p>Sometimes we just need a single instance of the python script to run at a time. Meaning, the python script itself should detects whether any instances of himself are still running and act accordingly.</p>
<p>Well, how to do it?</p>
<p>The idea is simple, the first instance of the python script will open a file, and lock it. Therefore when the consequent instances try to lock the file, it will fails.</p>
<p>The code is simple too.</p>
<pre><code>
import fcntl
def lockFile(lockfile):
    fp = open(lockfile, 'w')
    try:
        fcntl.lockf(fp, fcntl.LOCK_EX | fcntl.LOCK_NB)
    except IOError:
        return False

    return True
</code></pre>
<p>The function will try to lock the file specified by me, if it success, return True, else return False.</p>
<p>From any point of my codes, I&#8217;ll do</p>
<pre><code>
if not lockFile(".lock.pod"):
        sys.exit(0)
</code></pre>
<p>Interesting?</p>
<div class="aizatto_related_posts"><span class="aizatto_related_posts_header" >Related Posts</span><br/><span class="aizatto_related_posts_title" ><a href="http://linux.byexamples.com/archives/95/writting-executable-script/" rel="bookmark" title="Permanent Link: writting executable script" >writting executable script</a></span><div class="aizatto_related_posts_excerpt">Shell script (sh), Bash script (bash), Python and perl are all scripting language. By default, to run a scripting file, ...</div><p></p><span class="aizatto_related_posts_title" ><a href="http://linux.byexamples.com/archives/343/python-handle-string-from-pipelines-and-list-of-param/" rel="bookmark" title="Permanent Link: python: handle string from pipelines and list of param" >python: handle string from pipelines and list of param</a></span><div class="aizatto_related_posts_excerpt">While I was searching ways to implement pipeline input for my python apps, I read an article from linuxjournal.com that ...</div><p></p><span class="aizatto_related_posts_title" ><a href="http://linux.byexamples.com/archives/372/python-threading-callback-timer/" rel="bookmark" title="Permanent Link: Python: Threading Callback Timer" >Python: Threading Callback Timer</a></span><div class="aizatto_related_posts_excerpt">It is very common that we need to run certain routines periodically, thats why in *nix environment we have cron and in w...</div><p></p></div>
<p><a href="http://feedads.g.doubleclick.net/~a/kUW-Lef51OKknk545Kie-0NdHKM/0/da"><img src="http://feedads.g.doubleclick.net/~a/kUW-Lef51OKknk545Kie-0NdHKM/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/kUW-Lef51OKknk545Kie-0NdHKM/1/da"><img src="http://feedads.g.doubleclick.net/~a/kUW-Lef51OKknk545Kie-0NdHKM/1/di" border="0" ismap="true"></img></a></p><img src="http://feeds.feedburner.com/~r/LinuxByExamples/~4/SYPKk8Rri3c" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://linux.byexamples.com/archives/494/how-can-i-avoid-running-a-python-script-multiple-times-implement-file-locking/feed/</wfw:commentRss>
		<feedburner:origLink>http://linux.byexamples.com/archives/494/how-can-i-avoid-running-a-python-script-multiple-times-implement-file-locking/</feedburner:origLink></item>
	</channel>
</rss>
