Difference between revisions of "Short Notes on Python"

From PaskvilWiki
Jump to: navigation, search
(Importing Files)
Line 20: Line 20:
  
 
If you need to import a file '../mylib/commons.py', you can use the following snippet:
 
If you need to import a file '../mylib/commons.py', you can use the following snippet:
  <nowiki>fld = os.path.realpath(os.path.abspath(os.path.join('..', 'mylib')))
+
  <nowiki>import sys, os
 +
fld = os.path.realpath(os.path.abspath(os.path.join('..', 'mylib')))
 
if fld not in sys.path:
 
if fld not in sys.path:
 
     sys.path.insert(0, fld)
 
     sys.path.insert(0, fld)

Revision as of 10:41, 12 September 2012

Timing, and memory, on Linux

Timing

On Linux, it's safer to use time.time()

import time
t = time.time()
# do some stuff
print "stuff took %1.3f", time.time() - t, "seconds"

On Windows, AFAIK, it's safer to use time.clock()

Memory

For me, the following does a good job getting memory usage (in kB) on Linux:

import resource
print resource.getrusage(resource.RUSAGE_SELF).ru_maxrss

Since resource is standard package, it should work on Windows too, but I don't know if it does, or what units are used if it works.

Importing Files

If you need to import a file '../mylib/commons.py', you can use the following snippet:

import sys, os
fld = os.path.realpath(os.path.abspath(os.path.join('..', 'mylib')))
if fld not in sys.path:
    sys.path.insert(0, fld)
import commons

# use your commons.py module now...
commons.super_function()