简体   繁体   中英

How to get the current path of compiled binary from Python using Nuitka?

Nuitka is good at compiling Python to excutable binary. But the compiled binary finds other resource files from original absolute path. Thus, for moving to another computer requires to make the directory tree same as the original one.

For example, if I compile a project like this:

/home/me/myproj/
╠═ myprog.py
╚═ resource
   ╚═ foo.data

I should put the resulting binary and resource to the same location of another computer. How to solve this problem?

My simpler spike is:

# /home/me/myproj/spike.py
import os
print(os.path.dirname(__file__))

And after compiling it, moving to any other location, I always got the result of /home/me/myproj .

I need a result like /another/path if I move compiled myproj.bin to /another/path .

Another good function, is "--standalone" flag, which create one main ".bin" file + other ".so" dependencies in one folder. Which you can transfer beetween different machines.

Try using sys.argv[0] with os.path.abspath instead of __ file __ .

For example:

abs_pth = os.path.abspath(sys.argv[0])
your_dir = os.path.dirname(abs_pth)

for val in abs_pth,your_dir:
    print(val)

This will help you get the current path to the executable binary file, as well as work with directories located in the same folder.

https://pythonlang.dev/repo/nuitka-nuitka/#id42

Onefile: Finding files

There is a difference between sys.argv[0] and __ file __ of the main module for onefile more, that is caused by using a bootstrap to a temporary location. The first one will be the original executable path, where as the second one will be the temporary or permanent path the bootstrap executable unpacks to. Data files will be in the later location, your original environment files will be in the former location.

Given 2 files, one which you expect to be near your executable, and one which you expect to be inside the onefile binary, access them like this.

This will find a file near your onefile.exe open(os.path.join(os.path.dirname(sys.argv[0]), "user-provided-file.txt")) This will find a file inside your onefile.exe open(os.path.join(os.path.dirname(__ file __), "user-provided-file.txt"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM