views:

103

answers:

2

When writing a Python script that can be executed in different operating system environments (Windows/*nix), what are some good ways to set a path? In the example below I would like to have the logfiles stored in the logs folder under the current directory. Is this an acceptable approach (I'm rather new to Python) or are there better ways to achieve this? Thanks

if os.name == 'nt':
    logdir=('%s\\logs\\') % (os.getcwd())
else:
    logdir=('%s/logs/') % (os.getcwd())

logging.basicConfig(level=logging.INFO,
    format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
    datefmt='%m-%d-%y %H:%M:%S',
    filename='%slogfile.log' % (logdir),
    filemode='a')
+8  A: 

Definitely have a look at os.path. It contains many of the "safe" cross-OS path manipulation functions you need. For example, I've always done this in the scenario you're outlining:

os.path.join(os.path.abspath(os.path.dirname(__file__)), 'logs')

Also note that if you want to get the path separator, you can use:

os.path.sep

This will yield '\\' on Windows, and '/' on Linux, for example.

Ryan Duffield
Thanks Ryan. I ended up with the following based on your advice:os.path.join(os.path.abspath(os.path.dirname(__scriptname__)), 'logs') + (os.sep) This yielded the proper path with the correct slash at the end of the path.
Shaun
Glad to help! :-)
Ryan Duffield
+2  A: 

First, always use os.path for path manipulation.

More importantly, all paths should be provided in configuration files.

For logging, use the fileConfig function.

For everything else, be sure to have a configuration file or command-line parameter or environment variable.

S.Lott