Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to add script's working folder to import() path for Python on Windows?

I have a python program which I compile down to a Windows .exe using py2exe. Using Inno Setup, I create a Windows installer.

The nature of my program is such that it uses plugins which are later imported using the __import__() statement. These plugins are located in a 'plugins' folder, which itself is located as a subfolder of where my program's .exe file resides.

Now, to have the program find the plugins, it earlier had the following statement somwhere at the top of my file:

sys.path+= ['.']

However, this was not working well when the user started the program through Windows' start menu, because apparently the working folder was set to the start menu (instead of where the .exe is located). So '.' did not resolve to what I wanted.

I fixed it by changing the statement to the following, so that the __import__() statement also looks in the folder where the .exe is located (because argv[0] is the full path of the executable):

sys.path+= [os.path.dirname(sys.argv[0])]

However, I am not sure if I picked the right solution. Especially, because my program is meant to be cross-platform (Windows, OSX, Linux) and the sys.argv documentation says about argv[0] that 'it is operating system dependent whether this is a full pathname or not'.

Should I solve this differently, or is my approach OK?

like image 426
Rabarberski Avatar asked Feb 10 '12 11:02

Rabarberski


1 Answers

In my compiled to .exe Qt programms, I'm using code very similar to yours:

def executable_path():
    self_file = unicode(sys.argv[0], sys.getfilesystemencoding())
    return os.path.realpath(os.path.dirname(self_file))

I'm using unicode because path may contain non ascii symbols.

sys.argv[0] it is operating system dependent whether this is a full pathname or not

os.path.realpath solves that problem.

like image 186
reclosedev Avatar answered Sep 22 '22 13:09

reclosedev