Recent site activity

    Home‎ > ‎Computer‎ > ‎Python‎ > ‎

    Standard libraries

    OS

    System call without reading output:
    status = os.system('your commandline here')
    System call with reading output:
    content = os.popen('your command line here')
    print content.read()
    Alternative way using commands module:
    import commands
    out = commands.getoutput('ls -l')


    file

    Method seek() can be used to set file object's offset. fin.seek(0) will point the file object to start of the file.

    Data compression (gzip, bz2)

    Read and write data into compressed files using gzip or bzip2.
    >>> import gzip
    >>> fin = gzip.GzipFile('file.gz')
    >>> fout = gzip.GzipFile('out.gz','w')
    (following are similar with regular file objects)

    >>> import bz2
    >>> fin = bz2.BZ2File('a.bz2')
    (following are similar with regular file objects)

    urllib

    Open an URL address and check HTTP status code:
    url_handle = urllib.urlopen('http://localhost')
    print url_handle.getcode()

    Special characters needs to be escaped before they enter the URL string:
    a = 'Epigenomics Workshop - 9/09'
    print urllib.quote(a)
    print urllib.quote_plus(a) # more safe

    ftplib

    from ftplib import FTP
    ftp = FTP('ftp.ncbi.nih.gov')
    ftp.login()
    contents = []
    # change directory to
    ftp.cwd('/pub/geo/DATA/supplementary/samples/GSM537nnn/GSM537699/')

    # look what files exist under this dir
    # a callback function will be used to process returned contents
    ftp.dir(lambda x: contents.append(x))
    for cont in contents:
        print cont


    # and then look somewhere else
    ftp.cwd('/somewhere/else/')
    ftp.dir(lambda x: contents.append(x))
    print contents[-1]

    Encryption

    from hashlib import sha1
    token_str = sha1('a secret string to encrypt').hexdigest()
    print token_str

    Regular expression

    import re
    exp = re.compile(r'\[(..?)\]')
    a = '[12],[23],[34],,,'
    for i in exp.findall(a):
      print i

    CGI

    import cgi
    print "Content-Type: application/json"
    # or "text/html"
    print

    form = cgi.FieldStorage()

    if "trigger1" in form:
           value = form["trigger1"].value
           # do something...


    Comments