execute script in certain directory

vasudevram vasudevram at gmail.com
Mon Jul 9 13:14:07 EDT 2007


On Jul 9, 8:31 pm, brad <byte8b... at gmail.com> wrote:
> When I use idle or a shell to execute a python script, the script
> executes in the directory it is currently in (in this case, my desktop).
> However, when using GNOME and right clicking the py script and selecting
> 'open with python', the execution occurs in my home directory, not my
> desktop.
>
> Is there a way to force py scripts to always run within the directory
> that they reside in?
>
> Thanks
>
> Brad
>
> /home/brad/Desktop/output - python from shell
> /home/brad/Desktop/output - python from idle
> /home/brad/output - python from Gnome 'right click' open with menu

Any program that runs has a concept of a "current directory". All its
work is done relative to that, unless you open files with absolute
paths.

Don't know if there's a generic way to do what you want. (There may
be, just can't think of it right now). But there are specific ways -
script-specific, that is:

Add these lines to the top of your script:

import os
os.chdir(rundir)

# Replace rundir above with the absolute path (in quotes) of whatever
directory you want the script to have as its current directory when it
runs.

Looks like GNOME is doing a chdir to your home directory (probably for
convenience or security reasons) before running your script, thats why
you see that behaviour. This is why I say there may not be an easy
generic way to do it - because it would involve modifying all possible
execution environments from which your script could be launched. E.g.:
even if you modify GNOME to do what you want, how about if tomorrow
someone else wants to run your script from KDE or some other window
manager? these could do things differently.

HTH
Vasudev Ram
http://www.dancingbison.com
http://jugad.livejournal.com
http://sourceforge.net/projects/xtopdf





More information about the Python-list mailing list