parsed.org

Tips by tag: os

Create Directories Cleanly by cygnus on Jan 24, 2005 09:24 AM

os.mkdir raises a generic exception if an error occurs, but typically you need to ignore preexisting directory errors. Here's how to ignore them:

import os, errno, sys

myPath = "/path/to/dir"
try:
    os.mkdir(myPath)
except Exception, e:
    code, st = e
    if code != errno.EEXIST:
        st = "Error creating directory '%s': %s" % (myPath, str(e))
        sys.exit(1)
directoryexceptionslanguagesmkdirosprogrammingpython
os.system and Broken Pipes by cygnus on Dec 31, 2005 04:08 PM

If you're using os.system to run a command (such as xterm running man) and you get "broken pipe" errors, you can restore standard pipe functionality with the signal module:

import signal
signal.signal(signal.SIGPIPE, signal.SIG_DFL)

# Call os.system after calling signal.signal.

Note: information taken from http://monkeyfingers.org/ (page now unavailable).

brokenlanguagesospipeprogrammingpythonsignalsystemunix
Path Calculation by xinu on Mar 30, 2007 01:13 PM

If you need to tell a python framework where your templates, etc. are located, it helps to determine the location of the current module.

BASE_PATH = os.path.abspath(os.path.join(os.path.dirname(__FILE__), '..'))
TEMPLATES = os.path.join(BASE_PATH, 'templates')

Assuming you're running this code in /path/to/module.py, BASE_PATH will be set to /path. Other os.path tricks can be used to dynamically set paths in this way.

locationosparsingpathpython
RSS