newbie question: how to get directory of script?

Bengt Richter bokr at oz.net
Wed Nov 13 04:05:18 EST 2002


On 12 Nov 2002 09:57:43 -0800, animeshk at yahoo.com (animeshk) wrote:

>I'm sure this has been asked and answered a few zillion times: sorry!
>
>I want to be able to get the path of the script I am running (the idea
>is that I might have a data file or an ini file sitting in the same
>directory as the py file).  Okay . . . so how do I get it?  BTW, I am
>running Python 2.2.2 under Windows XP, with the wincom extensions.
>
>The docs said that sys.argv[0] should have the name of the script and,
>depending on the platform, the full path.  Nope: sys.argv[0] has the
>full path of python.exe (this is occurring within the Wing IDE
>environment, within PythonWin, and even from the command line).
>
>The docs also said that sys.path[0] should have the directory of the
>script.  Again, nope: it has the directory of python.exe.  However, I
>saw the directory of the script in sys.path[1].  Problem: this works
>fine from the command line and from within the Wing IDE, but not in
>PythonWin (PythonWin sets sys.path[1] to '').
>
>So . . . is there some "official"/"safe"/"standard" way of getting
>this information?  Thanks!

os.path.abspath(sys.argv[0]) would be my guess for the executing script.

What does the following do when you run it on your system from the
command line? On NT4 with Python 2.2.2, if I invoke it with python
or by file association with the script name only, I get the same output
to both screen and the junk.txt file. If I substitute pythonw in place
of python with the rest the same, there is no output to the screen, but
the file output is the same.

# pathtest.py
if __name__ == '__main__':
    import sys, os
    f = file('junk.txt','w', 0)
    print 'argv =', sys.argv
    f.write('argv = %s\n' % sys.argv)
    i = 0
    for arg in sys.argv:
        print '%2d: %s' % (i, os.path.abspath(arg))
        f.write('%2d: %s\n' % (i, os.path.abspath(arg)))
        i = i + 1
    f.close()

Regards,
Bengt Richter



More information about the Python-list mailing list