ms4py.blog

PyDev Interactive Console - set working directory

written on Wednesday, July 21, 2010

I often had the problem that the Interactive Console from Pydev does not start in the project source folder. On Windows, the working directory is per default:

>>> os.getcwd()
'C:\\Windows\\system32'

So I wrote a short script the set a working directory automatically which can be added to "Initial interpreter commands" under Preferences > Pydev > Interactive Console. Here it is:

import sys; print('%s %s' % (sys.executable or sys.platform, sys.version))
import os
base_path, _ = os.path.split(sys.executable)
cwd_path = [path for path in sys.path if base_path not in path
        and 'org.python.pydev' not in path and 'python26.zip' not in path]
if len(cwd_path) == 1:
    os.chdir(cwd_path[0])
else:
    # choose shortest path
    os.chdir(sorted(cwd_path, key=len)[0])

Please note, that there has to be two newlines (without any whitespaces, remove them!) at the end of the script. Otherwise the else-block wouldn't be left correctly.

This works fine if you doesn't have any custom paths in your PYTHONPATH environment variable.

This entry was tagged pydev


blog comments powered by Disqus