sys.argv[0] doesn't always contain the full path of running script.

Eyal Lotem eyal.lotem at gmail.com
Tue Aug 29 15:05:41 EDT 2006


>> How can I find where exactly the current python script is running?
>> ...
>> That means sys.argv[0] doesn't always contain the full path of
>> running script.
> sys.path[0] is the script directory, combined with sys.argv[0] you can
> find the full path to the script.
> (Note that in some rare cases sys.path[0] might not contain the script
> directory. For example in an executable created by py2exe).

I am not sure it is a good idea to rely on sys.path[0] being the current
directory.

I think the proper solution is to use: os.path.abspath(sys.argv[0])
If sys.argv[0] is a relative path, than adding cwd via the above function
will make it absolute as the gp wanted.

This may only break if the python program messes around with the cwd but in
that case its a good idea to extract os.path.abspath(sys.argv[0]) before
that.




More information about the Python-list mailing list