Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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.

like image 404
Renz Serrano Avatar asked Feb 19 '26 18:02

Renz Serrano


2 Answers

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://nuitka.net/doc/user-manual.html#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.

# 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"))
like image 99
SnakeСharming Avatar answered Feb 22 '26 14:02

SnakeСharming


Another good function to resolve __file__ problem, it is to use --standalone flag, which create one main ".bin" file + other ".so" dependencies in one folder.

python -m nuitka --standalone program.py

https://nuitka.net/doc/user-manual.html#use-case-4-program-distribution

like image 45
workmail20 Avatar answered Feb 22 '26 15:02

workmail20