Getting path of current script

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
hdtx
Posts: 3
Joined: Tue Oct 25, 2016 11:49 am

Getting path of current script

Post by hdtx » Tue Jan 10, 2017 4:48 pm

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)

User avatar
dhylands
Posts: 3821
Joined: Mon Jan 06, 2014 6:08 pm
Location: Peachland, BC, Canada
Contact:

Re: Getting path of current script

Post by dhylands » Tue Jan 10, 2017 6:18 pm

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.

hdtx
Posts: 3
Joined: Tue Oct 25, 2016 11:49 am

Re: Getting path of current script

Post by hdtx » Wed Jan 11, 2017 9:36 am

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.

User avatar
dhylands
Posts: 3821
Joined: Mon Jan 06, 2014 6:08 pm
Location: Peachland, BC, Canada
Contact:

Re: Getting path of current script

Post by dhylands » Wed Jan 11, 2017 7:41 pm

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__

hdtx
Posts: 3
Joined: Tue Oct 25, 2016 11:49 am

Re: Getting path of current script

Post by hdtx » Thu Jan 19, 2017 12:36 pm

Hi Dave,

I think os.getcwd will do. Thanks!

Post Reply