tag (python)

archive

pretty print json in python Jan
15
1
3

import json
mydata = json.loads(output)
print json.dumps(mydata, indent=4)

comments

ordinal number in python Jan
15
1
3

## {{{ http://code.activestate.com/recipes/576888/ (r10)
#!/usr/bin/env python

def ordinal(value):
    """
    Converts zero or a *postive* integer (or their string 
    representations) to an ordinal value.

    >>> for i in range(1,13):
    ...     ordinal(i)
    ...     
    u'1st'
    u'2nd'
    u'3rd'
    u'4th'
    u'5th'
    u'6th'
    u'7th'
    u'8th'
    u'9th'
    u'10th'
    u'11th'
    u'12th'

    >>> for i in (100, '111', '112',1011):
    ...     ordinal(i)
    ...     
    u'100th'
    u'111th'
    u'112th'
    u'1011th'

    """
    try:
        value = int(value)
    except ValueError:
        return value

    if value % 100//10 != 1:
        if value % 10 == 1:
            ordval = u"%d%s" % (value, "st")
        elif value % 10 == 2:
            ordval = u"%d%s" % (value, "nd")
        elif value % 10 == 3:
            ordval = u"%d%s" % (value, "rd")
        else:
            ordval = u"%d%s" % (value, "th")
    else:
        ordval = u"%d%s" % (value, "th")

    return ordval

if __name__ == '__main__':
    import doctest
    doctest.testmod()
## end of http://code.activestate.com/recipes/576888/ }}}

comments

including site packages in virtualenv 1.7 Jan
13
1
2

So if you're using virtualenv 1.7 and are wondering why you can no loger see your global Python site-packages directory it's because the default behavior has changed.

Now the default install for virtualenv is to hide site packages; equivalent to passing the old --no-site-packages command:

virtualenv --no-site-packages <env>

Since this option is now default it's no longer needed, and the new command to see the global site packages is --system-site-packages:

vitualenv --system-site-packages <env>

Hopefully this saves you some confusion as it's not clear what's happening when your new install now suddenly is breaking.

comments

random integer with a range in python Dec
14
1
1

To create a random integer within a range you can use the following command:

import random

# random integer between 1 and 100
RANDOM_INTEGER = random.randint(1, 100)

comments

create the directories if they don't exist in Python Sep
01
1
1

import os


directory = 'path/to/folder'

if not os.path.exists(directory):
    os.makedirs(directory)

comments

how to execute a string in python Sep
01
1
1

To run a string use `exec`

code = 'print "Hello World"'
exec code

If you need to pull a value from an expression use `eval`

foo = eval('1+1')

comments

how to stop / terminate / exit a python script Jan
03
1
1

I know this could be trivial to some of you, but it wasn't obvious to me which is why I'm posting. From time to time you might want to hard exit out of your python script. For me this came about when I was writing some system deploy and maintenance scripts. Just returning out of a function wasn't good enough because the rest of the script would keep on trucking. I needed to stop all execution of the script right there before it continued on and did irreversible damage to the system.

This can be done through the sys module.

import sys
sys.exit()

It's good to note that all this does is throws a SystemExit exception which can be caught like any other exception.

Alternatively you can use the os._exit() function which terminates at the C level and does not let the interpreter perform any of the normal tear-down procedures. It is not recommended to use os._exit() as sys.exit() should suffice for the vast majority of cases and is the recommended method.

comments

getting parent path of current directory in python Dec
10
1
0

The following code extracts the parent path of your current working directory, or any path value, in Python. I'm not sure if there's a way to automatically walk up and down through the directories, but this worked for me and was nice and small.

It works by splitting the path on "/", removes the last element in the array, then joins everything back together.

import os

path = os.getcwd()
parent_path = os.sep.join(path.split(os.sep)[:-1])

comments

stupid simple web server with python Dec
08
1
0

If you need to set up a basic web server really fast and you don't want to go through the hassle of setting up nginx, apache or another production-level web server you can just use Python. If you're lucky like me you're already developing in it anyway.

Python comes with a simple web server built in: SimpleHTTPServer

All you need to do is to change to the directory you want to host and call it:

cd /path/to/directory
python -m SimpleHTTPServer

That's all there is to it. You'll then be serving rooted to that directory. You can access it through localhost, 127.0.0.1, or your inet IP.

It will look for and automatically host index.html. If index.html isn't found then it will list the contents of the directory specified.

http://localhost:8000
http://192.168.1.###:8000

The default port is 8000, but you can easily change it. One things I use this for is when I need to initiate more than one simple server at once.

python -m SimpleHTTPServer 8080

Keep in mind that this is a single threaded server and it breaks easily. This most definitely should NOT be used in production.

Among other things this an easy way to transfer files between computers through your local network using only Python.

reference: http://www.linuxjournal.com/content/tech-tip-really-simple-http-server-python

comments

random string and digit generation in python Nov
17
1
0

This snippet generates a random string with digits with a defined LENGTH in Python. Useful for things like generating random passwords.

import os
import string


LENGTH = 6

password = ''.join(random.choice(string.ascii_letters + string.digits) for x in range(LENGTH))

comments

using the for loop counter in python Nov
17
1
0

Even with all the powerful tools Python loops do for you, sometimes you need to grab the good ol' loop counter.

There are a couple of different ways you can do this. The cleanest method that I found so far is to use the enumerate function. You can do something like this:

test = ['a', 'b', 'c']

for counter, value in enumerate(test):
    print counter, value

comments

extracting a class name from a python object Apr
01
1
0

You can dynamically extract an object's class name in Python like so:

my_object.__class__.__name__

comments