Trouble getting path of top level script file

My main file is this:


sys.path[0] return different value when I run the script file with only the dir and without the basename of the file.

I think the reliable way is to always run the script specifying the basename.

print('1', os.path.realpath(sys.argv[0]))
print('2', os.path.realpath(sys.path[0]))

$ python3 appdir
1 /Users/ljh/Documents/helloPy/src/appdir
2 /Users/ljh/Documents/helloPy/src/appdir
$ python3 -m appdir
1 /Users/ljh/Documents/helloPy/src/appdir/
2 /Users/ljh/Documents/helloPy/src

I think that the best way to get the directory of the running script is


Thanks Steven,

I read some on stackoverflow. some said that abspath does not resolve the symbol link and realpath points to the linked file.

Stackoverflow is not the official source of information :slight_smile:

realpath follows symlinks and junction points on Windows since Python 3.8 so it should be fine.