schlamar.blog

PyDev Interactive Console - Set Working Directory

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:

1
2
>>> 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:

1
2
3
4
5
6
7
8
9
10
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 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.