Q: The getcwd() doesn't return the directory that the source file is located.
Alex Martelli
aleaxit at yahoo.com
Sun Oct 29 06:42:04 EST 2000
More information about the Python-list mailing list
Sun Oct 29 06:42:04 EST 2000
- Previous message (by thread): Q: The getcwd() doesn't return the directory that the source file is located.
- Next message (by thread): ANN: AmigaPython 2.0
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
"Dale Strickland-Clark" <dale at out-think.NOSPAMco.uk> wrote in message news:2hvnvsgs713rj9assjrpefo1ifi7u6gv4q at 4ax.com... [snip] > >When I try the getcwd(), it returns the python2.0 root directory. > >How to get the current directory that the source file is located ? [snip] > Have you looked in sys.argv? > > import sys > print sys.argv[0] > > This prints the path to the source for me. It could print that path in an implied way, though, depending on exactly how it was specified on the invocation line. A more complete way to "get the directory in which the source file is located" (no "current" about it) could be: import sys, os.path as p print p.dirname(p.abspath(sys.argv[0])) However, this has to do with _the Python script that was originally loaded_, NOT the one from which instructions are currently being executed (which could well have been brought in with an import, quite possibly from a different directory). For any module that has been imported, the __file__ variable of that module should take the place of sys.argv[0] in the above construct. The variable will be undefined (a NameError will result, and can be caught, just as any other exception) in the main module (the one named '__main__', and named in sys.argv[0]). One still needs os.path.abspath to ensure an absolute path, and os.path.dirname to extract the directory name from it, of course. Alex
- Previous message (by thread): Q: The getcwd() doesn't return the directory that the source file is located.
- Next message (by thread): ANN: AmigaPython 2.0
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
More information about the Python-list mailing list