Page 1 of 1

Getting path of current script

Posted: Tue Jan 10, 2017 4:48 pm
by hdtx
Is there a way of getting the path of the currently executing script?

On the pyboard this simple main.py just prints an empty list for me ([]):

import sys
print(sys.argv)

Re: Getting path of current script

Posted: Tue Jan 10, 2017 6:18 pm
by dhylands
It looks like __file__ will do it.

If the file happens to be in the current directory, then __file__ returns a relative path. If it's in one of the sys.path directories, then it returns a fully qualified path.

Re: Getting path of current script

Posted: Wed Jan 11, 2017 9:36 am
by hdtx
Thanks for the answer Dave.

What I need to do is to find out if the current script is running from the internal flash or from the SD card. So the relative path thing is a problem. And __file__ is not defined for main.py.

I would like to be able to obtain the absolute path for the current running script, but just some other way of knowing whether it's on the flash or the SD would already help.

Re: Getting path of current script

Posted: Wed Jan 11, 2017 7:41 pm
by dhylands
I did notice that os.path.abspath isn't currently implemented, but it would be easy enough to implement. There is os.getcwd() (which will start with /flash or /sd)

In main.py os.getcwd() will be '/flash' or '/sd' depending on which device was booted from, and __name__ will be equal to __main__

Re: Getting path of current script

Posted: Thu Jan 19, 2017 12:36 pm
by hdtx
Hi Dave,

I think os.getcwd will do. Thanks!