executing python scripts that are symlinked

Steven D'Aprano steve+comp.lang.python at pearwood.info
Thu May 16 05:04:02 EDT 2013


On Thu, 16 May 2013 00:48:45 -0700, Charles Smith wrote:

> Hi.
> 
> How can I say, from the cmd line, that python should take my CWD as my
> CWD, and not the directory where the script actually is?

*scratches head*

Python does use your current working directory as your current working 
directory. I think you are misdiagnosing the problem.

Here's a demonstration:

steve at runes:~$ cat test.py
import os
print os.getcwd()


steve at runes:~$ ln -s ~/test.py /tmp/test
steve at runes:~$ ls -l /tmp/test 
lrwxrwxrwx 1 steve steve 19 May 16 18:58 /tmp/test -> /home/steve/test.py
steve at runes:~$ cd /etc/
steve at runes:/etc$ python /tmp/test 
/etc


> I have a python script that works fine when it sits in directory WC, but
> if I move it out of WC to H and put a symlink from H/script to WC, it
> doesn't find the packages that are in WC.  Also, if I use the absolute
> path to H, it won't find them, but I guess I can understand that.

The obvious solution is to make sure that WC is in the Python path. You 
can do that by adding it the environment variable PYTHONPATH, or by 
adding it to sys.path at the start of your script. I think you can also 
use a .pth file as well.

Another solution may be to add this to the beginning of your script:

os.setcwd('path/to/WC')

but that's a crappy solution, you generally don't want to be changing the 
working directory from inside scripts if you can avoid it.



-- 
Steven



More information about the Python-list mailing list