Thursday, August 7, 2008

Python : Working Directory Woes

Python has unittest that allows you to have a framework for testing your modules.
There is also nosetests. If you are using Wing IDE, there is a built in Test panel.
All is beautiful.

The problem is, if your project uses calls to "locate directory of where your script ran" you're in for a ride. Unlike windows api where u have a definite api to get this, the various ways in python to get the value resides in os.sys.path[0], sys.argv[0] and os.getcwd().

ALL the values you have seen will not get you the values you want, in unix when its run by using python or using the crond or when you run it from another script located elsewhere or in windows when you run it with "unittest, nosetests and even the Wing's Test panel" these values are going to give you a different result.

And then there is the py2exe ....which will give you yet another surprise as the path return is "\dist\library.zip"

Solution :

Temporarily put some guards for tests enviroment and use the following :-

def GetCurrentWorkingDir () :

if "Wing" in sys.argv[0] : return os.sys.path[0] + os.sep
if "nosetests" in sys.argv[0] : return os.sys.path[0] + os.sep

return os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]))) + os.sep

2 comments:

  1. hi,

    I have a few python projects that i'm looking to outsource. How can i contact you?

    Thanks
    Stewart

    ReplyDelete
  2. This comment has been removed by a blog administrator.

    ReplyDelete