Python

From Torben's Wiki
Jump to: navigation, search


Contents

Basics

# delete a variable
del var
# check if variable is defined
if xyz in locals() :
# for object oriented projects:
if "xyz" in self.__dict__.keys(): 

Strings

# num <-> str
s= str (i) # int to string
f = float("1.234") # str -> float
str(round(f, 1)) # round first 

text = text.strip() # trim spaces

text = prompt("Enter Text: ") # get string from prompt

print "Renner =", i

# handling substrings
a = "abcd"
b = a[:1] + "o" + a[2:] 
> 'aocd'

# find a substring:
x in s
> True / False

s * 5
>>> s+s+s+s+s

s.replace(x, y)

# convert int i to string with leading zeros if i<100
print "%03d" % (i)

# place formatted numbers in a string / sprintf
"The %i %s cost %f euros" % (3, "beers", 11.50)
> 'The 3 beers cost 11.500000 euros'

"The length is %.2f meters" % 72.8958
>'The length is 72.90 meters'

p= "%.1f%%/min" % precent

Find a substring
myString="Hello there !bob@"
mySubString=myString[myString.find("!")+1:myString.find("@")]

the string lib

import string
string.capwords(s) # upper case first letter of each word and also removes multiple and trailing spaces

Lists

like arrays in Perl

L = [1,2,3,4,5,6]
L = [x for x in range(10)]
L = s.split () # split string s by spaces, use (s.split(",")) to split on "," etc
len(L)
L[0:10] # get elements 0-10

M = L[:] # copy L
M = L # link list M->L
L.append(x) # append a single element
L.extend(M) # put elements of list M to the end of List L
L.insert(i, x) # insert item x at position int i
L.pop() # returns and removes the last item
L.pop(i) # returns and removes the item at position int i
L.reverse()
L.sort()
L.remove(x) # removes the first occurrence of item x
L.count(x) # how many items x are in the list
L.index(x) # gives the position of the first x in list
s="".join(L)
x in L 
x not in L

# List to string
"\n".join(L)

Tupels

Ordered sequence, with no ability to replace or delete items

L = (1,2,3,4,5,6)

Dictionaries

like hash in Perl

d = {'keyx': valuex, 'keyy': valuey}
d['keyz'] = valuez
tel.keys()
['keyx', 'keyy', 'keyz']
del d['keyy']

len(d)
d.clear()
d.copy()
d.keys()
d.values()
d.items() # returns a list of tuples (key, value)
d.get(k) # returns value of key k
d.get(k, x) # returns value of key k; if k is not in d it returns x
d.pop(k) # returns and removes item k
d.pop(k, x) # returns and removes item k; if k is not in d it returns x
x in d
x not in d

Loops

while i <= 100:
  ...
  if sth:
    break

for i in range(1, 5):
  print i
  if sth:
    continue
else:
  print 'The for loop is over'

for f in files :

Imports

import sys
import datetime
import time
import math
import random
import os.path
import MyFile # without tailing .py
# import a file, not stored in the same folder
import sys
sys.path.append("../MyPyLibs") # here we find ipHelp.py and Devices.py

Math

get rid of the annoying integer division: [1]

from __future__ import division

Date and Time

http://pleac.sourceforge.net/pleac_python/datesandtimes.html

import datetime
d = datetime.date.today().strftime("%y%m%d")
d = datetime.datetime.today().strftime("%y%m%d-%H%M")

sleep for a while

import time
time.sleep(60)

wait for user input

raw_input("Press Enter to close")

calculate time

import time
duration = 1234 # sec
print "ETA =",time.ctime(time.time()+duration)
array = time.localtime(time.time()+duration)

File Access

http://www.penzilla.net/tutorials/python/fileio/

Get filename of python script

from sys import argv
myFilename = argv[0]

Read filename from commandline parameter

import sys
for filename in sys.argv:

Write to file

filename = "test.dat"
FILE = open(filename,"w") # w = overWrite file ; a = append to file
FILE.writelines(list)
# or
for line in list:
  FILE.write(line)
FILE.close()

Force update of filecontents without closing it

FILE.flush()

Read file

FILE = open(filename,"r")
list = FILE.read()
# or
line =  FILE.readline()
FILE.close()

Touch file

if os.path.exists(fname):
  os.utime(fname, None)
else:
  open(fname, 'w').close()

Read Timestamp (last modified)

lasttime = os.path.getmtime(fname)

Check if file / dir exists

import os.path  # os.path - The key to File I/O
os.path.exists("text.txt")
os.path.isfile("text.txt")
os.path.isdir("text")
os.path.isabs("/home/torben/text.txt") # Is it an absolute path

make dirs

if not os.path.isdir(d) :
  os.mkdir(d) # normal
  os.makedirs(d) # recursively= with all parents

Delete folder+contents

import shutil
shutil.rmtree(d)

Cross platform paths

currentdir = os.curdir
mysubdir = os.path.join(currentdir, "mysubdir")

Get list of files (not dirs) in directory

dirname = "/path/to/some/dir"
listoffiles = [ f for f in os.listdir(dirname) if os.path.isfile(dirname+"/"+f) ]
listoffiles.sort()

Get file size

import os
int (os.path.getsize("moinsen.txt") )

Split path into folder, filename, ext

(dirName, fileName) = os.path.split(f)
(fileBaseName, fileExtension)=os.path.splitext(fileName)

Run external program

if os.path.isfile(ausgabedatei) :
  os.system("gnuplot " + ausgabedatei )

Checking Operating System

import os
import sys
if os.name == 'posix':
  print 'posix/Unix/Linux'
elif os.name == 'nt':
  print 'windows'
else:
  print 'unknown os'
  sys.exit(1)

Exceptions

Catch keyboard interrupt and do a "save exit"

try:
  FILE = open("out.txt","w")
  while 1:
    i+=1
    print i
except KeyboardInterrupt:
  FILE.close()

Catch all exceptions

try:
  [...]
except Exception, e:
  print "Exception raised: ", e

Custom Exceptions

try: 
  raise Exception('HiHo')

Debugging

Carsten Knoll wrote a nice module that improves the display of execeptions and allows to open an ipython shell at a certain point of the program code:

# ipHelp.py
# by Carsten Knoll
import sys
import new
__version__ = "0.2"
try:
    from IPython.Shell import IPShellEmbed
    args = ['-pi1','In <\\#>: ','-pi2','   .\\D.: ',
                '-po','Out<\\#>: ','-nosep']
    class AdaptedIPSE(IPShellEmbed):
        def __init__(self, *args, **kwargs):

            IPShellEmbed.__init__(self, *args, **kwargs)
            old_interact = self.IP.interact # save the real method
            def new_interact(self, *args):
                self.IP.user_ns.update({'_ips_exit':False})
                old_interact(*args) # call the real interact method
                if self.IP.user_ns['_ips_exit']:
                    def do_nothing(*args, **kwargs):
                        pass
                    self.IP.interact = do_nothing
            self.IP.interact = new.instancemethod(new_interact, self,
                                                                  type(self))
    IPS= AdaptedIPSE(args,
                           banner = 'Dropping into IPython',
                           exit_msg = 'Leaving Interpreter, back to program.')
    def ip_syshook(pdb=0, mode=2):
        import IPython.ultraTB
        modus = ['Plain', 'Context', 'Verbose'][mode] # select the mode
        sys.excepthook = IPython.ultraTB.FormattedTB(mode=modus,
                                        color_scheme='Linux', call_pdb=pdb)

    def ip_extra_syshook(fnc, pdb=0, filename=None):
        assert callable(fnc)
        import IPython.ultraTB
        import time
        if not filename == None:
            assert isinstance(filename, str)
            pdb = 0
        ip_excepthook = IPython.ultraTB.FormattedTB(mode='Verbose',
                                        color_scheme='Linux', call_pdb=pdb)
        fileTraceback = IPython.ultraTB.FormattedTB(mode='Verbose',
                                        color_scheme='NoColor', call_pdb=0)
        def theexecphook (type, value, traceback):
            fnc()
            ip_excepthook(type, value, traceback)
            # write this to a File without Colors
            if not filename == None:
                outFile = open(filename, "a")
                outFile.write("--" + time.ctime()+" --\n")
                outFile.write(fileTraceback.text(type, value, traceback))
                outFile.write("\n-- --\n")
                outFile.close()
        sys.excepthook = theexecphook
    from IPython.Debugger import Tracer
    ST=Tracer()
except ImportError:
    # create dummy functions
    def IPS():
        print "(EE): IPython is not available"
        pass
    def ip_syshook(*args):
        pass

    def ST():
        pass

Now include this file in your project and place IPS() somewhere in your code to open a shell there.

from ipHelp import IPS, ip_syshook
ip_syshook() # (1) -> debugger on exception
# run IPS() somewhere to open ipython shell

If you have are unsing PyQT and you get the message "QCoreApplication::exec: The event loop is already running", inserting the following into your __init__ of your main class will help:

QtCore.pyqtRemoveInputHook()
Personal tools