Nuitka使
Gyazo

Python nuitka
nuitka

Nuitka
NuitkaPythonNuitka PythonCPython 2.6, 2.7, 3.3, 3.4, 3.5, 3.6, 3.7, 3.8, 3.9 Python


Python使

NuitkaPythonClibpythonC使CPython

PythonNuitka

Nuitka --standalone --onefile 使Python
Nitka Windows .exe ) .bin OS -e
CPythonAnaconda Python
NuitkaPythonCPythonPythonWindowsPythonPythonPythonXX.DLLNuitka
WindowsPython
WindowsPythonNuitka Python macOS "pyenv "
OSLinuxFreeBSDNetBSDmacOS XWindows32/64
OSScion使WindowsPythonC
x86, x86_64 (amd64), arm,
Nuitka 使Debian

Nuitka pip

$ pip install nuitka

URL



nuitka pip Python nuitka3
Python

$ python -m nuitka

--help

% nuitka3 --help
Usage: nuitka3 [--module] [--run] [options] main_module.py
nuitka3: error: no such option: --hepl
(py39) goichiiisaka@GoichiMacBook answer % nuitka3 --help
Usage: nuitka3 [--module] [--run] [options] main_module.py
Options:
--version show program's version number and exit
-h, --help show this help message and exit
--module Create an extension module executable instead of a
program. Defaults to off.
--standalone Enable standalone mode for output. This allows you to
transfer the created binary to other machines without
it using an existing Python installation. This also
means it will become big. It implies these option: "--
follow-imports". You may also want to use "--python-
flag=no_site" to avoid the "site.py" module, which can
save a lot of code dependencies. Defaults to off.
--onefile On top of standalone mode, enable onefile mode. This
means not a folder, but a compressed executable is
created and used. Defaults to off.
--python-debug Use debug version or not. Default uses what you are
using to run Nuitka, most likely a non-debug version.
--python-flag=PYTHON_FLAGS
Python flags to use. Default uses what you are using
to run Nuitka, this enforces a specific mode. These
are options that also exist to standard Python
executable. Currently supported: "-S" (alias
"nosite"), "static_hashes" (do not use hash
randomization), "no_warnings" (do not give Python
runtime warnings), "-O" (alias "noasserts"). Default
empty.
--python-for-scons=PYTHON_SCONS
If using Python3.3 or Python3.4, provide the path of a
Python binary to use for Scons. Otherwise Nuitka can
use what you run Nuitka with or a "scons" binary that
is found in PATH, or a Python installation from
Windows registry.
--warn-implicit-exceptions
Enable warnings for implicit exceptions detected at
compile time.
--warn-unusual-code Enable warnings for unusual code detected at compile
time.
--assume-yes-for-downloads
Allow Nuitka to download code if necessary, e.g.
dependency walker on Windows.
Control the inclusion of modules and packages in result.:
--include-package=PACKAGE
Include a whole package. Give as a Python namespace,
e.g. ``some_package.sub_package`` and Nuitka will then
find it and include it and all the modules found below
that disk location in the binary or extension module
it creates, and make it available for import by the
code. Default empty.
--include-module=MODULE
Include a single module. Give as a Python namespace,
e.g. ``some_package.some_module`` and Nuitka will then
find it and include it in the binary or extension
module it creates, and make it available for import by
the code. Default empty.
--include-plugin-directory=MODULE/PACKAGE
Include the content of that directory, no matter if
it's used by the given main program in a visible form.
Overrides all other recursion options. Can be given
multiple times. Default empty.
--include-plugin-files=PATTERN
Include into files matching the PATTERN. Overrides all
other follow options. Can be given multiple times.
Default empty.
--prefer-source-code
For already compiled extension modules, where there is
both a source file and an extension module, normally
the extension module is used, but it should be better
to compile the module from available source code for
best performance. If not desired, there is --no-
prefer-source-code to disable warnings about it.
Default off.
Control the following into imported modules:
--follow-stdlib Also descend into imported modules from standard
library. This will increase the compilation time by a
lot. Defaults to off.
--nofollow-imports When --nofollow-imports is used, do not descend into
any imported modules at all, overrides all other
recursion options. Defaults to off.
--follow-imports When --follow-imports is used, attempt to descend into
all imported modules. Defaults to off.
--follow-import-to=MODULE/PACKAGE
Follow to that module if used, or if a package, to the
whole package. Can be given multiple times. Default
empty.
--nofollow-import-to=MODULE/PACKAGE
Do not follow to that module name even if used, or if
a package name, to the whole package in any case,
overrides all other options. Can be given multiple
times. Default empty.
Data files for standalone/onefile mode:
--include-package-data=PACKAGE_DATA
Include data files of the given package name. Can use
patterns. By default Nuitka does not unless hard coded
and vital for operation of a package. This will
include all non-DLL, non-extension modules in the
distribution. Default empty.
--include-data-file=DATA_FILES
Include data files by filenames in the distribution.
There are many allowed forms. With '--include-data-
file=/path/to/file/*.txt=folder_name/some.txt' it will
copy a single file and complain if it's multiple. With
'--include-data-
file=/path/to/files/*.txt=folder_name/' it will put
all matching files into that folder. For recursive
copy there is a form with 3 values that '--include-
data-file=/path/to/scan=folder_name=**/*.txt' that
will preserve directory structure. Default empty.
--include-data-dir=DATA_DIRS
Include data files from complete directory in the
distribution. This is recursive. Check '--include-
data-file' with patterns if you want non-recursive
inclusion. An example would be '--include-data-
dir=/path/somedir=data/somedir' for plain copy, of the
whole directory. All files are copied, if you want to
exclude files you need to remove them beforehand.
Default empty.
Immediate execution after compilation:
--run Execute immediately the created binary (or import the
compiled module). Defaults to off.
--debugger, --gdb Execute inside a debugger, e.g. "gdb" or "lldb" to
automatically get a stack trace. Defaults to off.
--execute-with-pythonpath
When immediately executing the created binary
(--execute), don't reset PYTHONPATH. When all modules
are successfully included, you ought to not need
PYTHONPATH anymore.
Dump options for internal tree:
--xml Dump the final result of optimization as XML, then
exit.
Code generation choices:
--full-compat Enforce absolute compatibility with CPython. Do not
even allow minor deviations from CPython behavior,
e.g. not having better tracebacks or exception
messages which are not really incompatible, but only
different. This is intended for tests only and should
not be used for normal use.
--file-reference-choice=FILE_REFERENCE_MODE
Select what value "__file__" is going to be. With
"runtime" (default for standalone binary mode and
module mode), the created binaries and modules, use
the location of themselves to deduct the value of
"__file__". Included packages pretend to be in
directories below that location. This allows you to
include data files in deployments. If you merely seek
acceleration, it's better for you to use the
"original" value, where the source files location will
be used. With "frozen" a notation "<frozen
module_name>" is used. For compatibility reasons, the
"__file__" value will always have ".py" suffix
independent of what it really is.
Output choices:
-o FILENAME Specify how the executable should be named. For
extension modules there is no choice, also not for
standalone mode and using it will be an error. This
may include path information that needs to exist
though. Defaults to '<program_name>' on this platform.
.bin
--output-dir=DIRECTORY
Specify where intermediate and final output files
should be put. The DIRECTORY will be populated with C
files, object files, etc. Defaults to current
directory.
--remove-output Removes the build directory after producing the module
or exe file. Defaults to off.
--no-pyi-file Do not create a ".pyi" file for extension modules
created by Nuitka. This is used to detect implicit
imports. Defaults to off.
Debug features:
--debug Executing all self checks possible to find errors in
Nuitka, do not use for production. Defaults to off.
--unstripped Keep debug info in the resulting object file for
better debugger interaction. Defaults to off.
--profile Enable vmprof based profiling of time spent. Not
working currently. Defaults to off.
--graph Create graph of optimization process. Defaults to off.
--trace-execution Traced execution output, output the line of code
before executing it. Defaults to off.
--recompile-c-only This is not incremental compilation, but for Nuitka
development only. Takes existing files and simply
compile them as C again. Allows compiling edited C
files for quick debugging changes to the generated
source, e.g. to see if code is passed by, values
output, etc, Defaults to off. Depends on compiling
Python source to determine which files it should look
at.
--generate-c-only Generate only C source code, and do not compile it to
binary or module. This is for debugging and code
coverage analysis that doesn't waste CPU. Defaults to
off. Do not think you can use this directly.
--experimental=EXPERIMENTAL
Use features declared as 'experimental'. May have no
effect if no experimental features are present in the
code. Uses secret tags (check source) per experimented
feature.
Backend C compiler choice:
--clang Enforce the use of clang. On Windows this requires a
working Visual Studio version to piggy back on.
Defaults to off.
-j N, --jobs=N Specify the allowed number of parallel C compiler
jobs. Defaults to the system CPU count.
--lto Use link time optimizations if available and usable
(MSVC, gcc >=4.6, clang). Defaults to off.
--static-libpython=STATIC_LIBPYTHON
Use static link library of Python if available.
Defaults to auto, i.e. enabled for where we know it's
working.
Tracing features:
--quiet Disable all information outputs, but show warnings.
Defaults to off.
--show-scons Operate Scons in non-quiet mode, showing the executed
commands. Defaults to off.
--show-progress Provide progress information and statistics. Defaults
to off.
--no-progress Disable progress bar outputs (if tqdm is installed).
Defaults to off.
--show-memory Provide memory information and statistics. Defaults to
off.
--show-modules Provide information for included modules and DLLs
Defaults to off.
--show-modules-output=SHOW_INCLUSION_OUTPUT
Where to output --show-modules, should be a filename.
Default is standard output.
--verbose Output details of actions taken, esp. in
optimizations. Can become a lot. Defaults to off.
--verbose-output=VERBOSE_OUTPUT
Where to output --verbose, should be a filename.
Default is standard output.
Windows specific controls:
--windows-disable-console
When compiling for Windows, disable the console
window. Defaults to off.
--windows-icon-from-ico=ICON_PATH
Add executable icon. Can be given multiple times for
different resolutions or files with multiple icons
inside. In the later case, you may also suffix with
#<n> where n is an integer index starting from 1,
specifying a specific icon to be included, and all
others to be ignored.
--windows-icon-from-exe=ICON_EXE_PATH
Copy executable icons from this existing executable
(Windows only).
--windows-uac-admin
Request Windows User Control, to grant admin rights on
execution. (Windows only). Defaults to off.
--windows-uac-uiaccess
Request Windows User Control, to enforce running from
a few folders only, remote desktop access. (Windows
only). Defaults to off.
--windows-company-name=WINDOWS_COMPANY_NAME
Name of the company to use in Windows Version
information. One of file or product version is
required, when a version resource needs to be added,
e.g. to specify product name, or company name.
Defaults to unused.
--windows-product-name=WINDOWS_PRODUCT_NAME
Name of the product to use in Windows Version
information. Defaults to base filename of the binary.
--windows-file-version=WINDOWS_FILE_VERSION
File version to use in Windows Version information.
Must be a sequence of up to 4 numbers, nothing else
allowed. One of file or product version is required,
when a version resource needs to be added, e.g. to
specify product name, or company name. Defaults to
unused.
--windows-product-version=WINDOWS_PRODUCT_VERSION
Product version to use in Windows Version information.
Must be a sequence of up to 4 numbers, nothing else
allowed. One of file or product version is required,
when a version resource needs to be added, e.g. to
specify product name, or company name. Defaults to
unused.
--windows-file-description=WINDOWS_FILE_DESCRIPTION
Description of the file use in Windows Version
information. One of file or product version is
required, when a version resource needs to be added,
e.g. to specify product name, or company name.
Defaults to nonsense.
--windows-onefile-tempdir-spec=ONEFILE_TEMPDIR_SPEC
Use this as a temporary folder. Defaults to
'%TEMP%\onefile_%PID%_%TIME%', i.e. system temporary
directory.
--windows-force-stdout-spec=WINDOWS_FORCE_STDOUT_SPEC
Force standard output of the program to go to this
location. Useful for programs with disabled console
and programs using the Windows Services Plugin of
Nuitka. Defaults to not active, use e.g.
'%PROGRAM%.out.txt', i.e. file near your program.
--windows-force-stderr-spec=WINDOWS_FORCE_STDERR_SPEC
Force standard error of the program to go to this
location. Useful for programs with disabled console
and programs using the Windows Services Plugin of
Nuitka. Defaults to not active, use e.g.
'%PROGRAM%.err.txt', i.e. file near your program.
Linux specific controls:
--linux-onefile-icon=ICON_PATH
Add executable icon for onefile binary to use. Can be
given only one time. Defaults to Python icon if
available.
Plugin control:
--plugin-enable=PLUGINS_ENABLED, --enable-plugin=PLUGINS_ENABLED
Enabled plugins. Must be plug-in names. Use --plugin-
list to query the full list and exit. Default empty.
--plugin-disable=PLUGINS_DISABLED, --disable-plugin=PLUGINS_DISABLED
Disabled plugins. Must be plug-in names. Use --plugin-
list to query the full list and exit. Default empty.
--plugin-no-detection
Plugins can detect if they might be used, and the you
can disable the warning via --plugin-disable=plugin-
that-warned, or you can use this option to disable the
mechanism entirely, which also speeds up compilation
slightly of course as this detection code is run in
vain once you are certain of which plug-ins to use.
Defaults to off.
--plugin-list Show list of all available plugins and exit. Defaults
to off.
--user-plugin=USER_PLUGINS
The file name of user plugin. Can be given multiple
times. Default empty.

nuitka-run 使 nuitka Python

--help



def talk(message):
return "Talk " + message
def main():
print(talk("Hello World"))
if __name__ == "__main__":
main()

Python

% python helloworld.py
Talk Hello World

nuitka

% python -m nuitka helloworld.py
Nuitka-Options:INFO: Used command line options: helloworld.py
Nuitka:INFO: Starting Python compilation with Nuitka '0.6.16.4' on Python '3.9' commercial None.
Nuitka:INFO: Completed Python level compilation and optimization.
Nuitka:INFO: Generating source code for C backend compiler.
Nuitka:INFO: Running data composer tool for optimal constant value handling.
Nuitka:INFO: Running C level backend compilation via Scons.
Nuitka-Scons:INFO: Backend C compiler: clang (clang).
Nuitka will make use of ccache to speed up repeated compilation.
Is it OK to download and put it in '/Users/goichiiisaka/Library/Application Support/Nuitka/ccache/v4.2.1'.
No installer needed, cached, one time question.
Proceed and download? [Yes]/No
Nuitka:INFO: Downloading 'https://nuitka.net/ccache/v4.2.1/ccache-4.2.1.zip'.
Nuitka:INFO: Extracting to '/Users/goichiiisaka/Library/Application Support/Nuitka/ccache/v4.2.1/ccache'
Nuitka-Scons:INFO: Compiled 12 C files using ccache.
Nuitka-Scons:INFO: Cached C files (using ccache) with result 'disabled': 1
Nuitka-Scons:INFO: Cached C files (using ccache) with result 'cache miss': 11
Nuitka:INFO: Keeping build directory 'helloworld.build'.
Nuitka:INFO: Successfully created 'helloworld.bin'.
%

ccache
bin build
Windows .exe

% ls
helloworld.bin helloworld.build helloworld.py

bin
PATH
Python


% file ./helloworld.bin
./helloworld.bin: Mach-O 64-bit executable x86_64
% ./helloworld.bin
Talk Hello World
% env PATH=. helloworld.bin
Talk Hello World

Python 使使()Python 使C


$ uname -a
Linux dev01 3.10.0-1160.31.1.el7.x86_64 #1 SMP Thu Jun 10 13:32:12 UTC 2021 x86_64 x86_64 x86_64 GNU/Linux
$ file ./helloworld.bin
./helloworld.bin: Mach-O 64-bit executable
$ chmod 700 ./helloworld.bin
$ ./helloworld.bin
-bash: ./helloworld.bin: cannot execute binary file


--standalone hello.dist

--onefile --onefile 使 --standalone

% ls
helloworld.bin helloworld.dist
helloworld.build helloworld.py
% ls helloworld.dist
_asyncio.so _lzma.so helloworld
_bisect.so _multibytecodec.so lib2to3
_blake2.so _multiprocessing.so libcrypto.1.1.dylib
_bz2.so _opcode.so libffi.7.dylib
_codecs_cn.so _pickle.so liblzma.5.dylib
_codecs_hk.so _posixshmem.so libncursesw.6.dylib
_codecs_iso2022.so _posixsubprocess.so libpanelw.6.dylib
_codecs_jp.so _queue.so libpython3.9.dylib
_codecs_kr.so _random.so libreadline.8.dylib
_codecs_tw.so _scproxy.so libsqlite3.0.dylib
_contextvars.so _sha512.so libssl.1.1.dylib
_crypt.so _socket.so libtcl8.6.dylib
_csv.so _sqlite3.so libtk8.6.dylib
_ctypes.so _ssl.so libz.1.dylib
_curses.so _statistics.so math.so
_curses_panel.so _struct.so mmap.so
_datetime.so _tkinter.so pyexpat.so
_dbm.so _uuid.so readline.so
_decimal.so _zoneinfo.so select.so
_elementtree.so array.so termios.so
_hashlib.so audioop.so unicodedata.so
_heapq.so binascii.so zlib.so
_json.so fcntl.so
_lsprof.so grp.so


1 -


$ python -m nuitka --follow-imports helloworld.py

PYTHONPATH

$ python -m nuitka --follow-imports --include-plugin-directory=plugin_dir program.py

PYTHONPATH
--include-plugin-directory Nuitka __import__() 使Nuitka

CPython使C

--standalone 使 program.dist program.exe Windows program

-
1

$ python -m nuitka --module some_module.py

--module --follow-imports
--follow-imports some_module
CPython

3 -
Nuitka

$ python -m nuitka --module some_package --include-package=some_package


4 -
--standalone

$ python -m nuitka --standalone program.py

--nofollow-import-to ImportError

--include-data-file=<source>=<target> 使source target onefile

--include-data-file=/etc/*.txt=etc/ 使

--include-data-dir=/path/to/images=images 使

--include-package-data 使

Nuitka

使

$ python -m nuitka --onefile program.py

Linux使

Windows使 --windows-onefile-tempdir-spec=%TEMP%\onefile_%PID%_%TIME%


Windows

%TEMP% 使 C:Users...AppDataLocalsTemp
%PID% ID 2772
%TIME% 1299852985
%PROGRAM% () C:SomeWhereYourOnefile.exe

WindowsOS使

%TIME% %PID% 使使

WindowsPNG

python -m nuitka --onefile --windows-icon-from-ico=your-icon.png program.py
python -m nuitka --onefile --windows-icon-from-ico=your-icon.ico program.py
python -m nuitka --onefile --windows-icon-template-exe=your-icon.ico program.py

(splash screen)便Onefile使NuitkaWindows

PNG使

# nuitka-project: --onefile
# nuitka-project: --onefile-windows-splash-screen-image={MAIN_DIRECTORY}/Splash-Screen.png
print("Delaying startup by 10s...")
import time
time.sleep(10)
# Use this code to signal the splash screen removal.
if "NUITKA_ONEFILE_PARENT" in os.environ:
splash_filename = os.path.join(
tempfile.gettempdir(),
"onefile_%d_splash_feedback.tmp" % int(os.environ["NUITKA_ONEFILE_PARENT"]),
)
if os.path.exists(splash_filename):
os.unlink(splash_filename)
print("Done... splash should be gone.")
# ...

sys.path
sys.path Nuitka PYTHONPATH

VERSIONunknown

使

DLL
NuitkaDLLNumPySciPyTkinter

NumPy使

Nuitka1000Pandas使

Nuitka使

anti-bloat
--enable-plugin=anti-bloat --noinclude-pytest-mode=nofollow --noinclude-setuptools-mode=nofollow 使 PyQt5

sys.argv[0] __file__ 使 sys.argv[0] __file__

2

# onefile.exe
open(os.path.join(os.path.dirname(sys.argv[0]), "user-provided-file.txt"))
# onefile.exe
open(os.path.join(os.path.dirname(__file__), "user-provided-file.txt"))


使Windows
--windows-disable-console --windows-force-stdout-spec --windows-force-stderr-spec --windows-onefile-tempdir-spec 使

使

# Compilation mode, support OS specific.
# nuitka-project-if: {OS} in ("Windows", "Linux", "Darwin", "FreeBSD"):
# nuitka-project: --onefile
# nuitka-project-if: {OS} not in ("Windows", "Linux", "Darwin", "FreeBSD"):
# nuitka-project: --standalone
# The PySide2 plugin covers qt-plugins
# nuitka-project: --enable-plugin=pyside2
# nuitka-project: --include-qt-plugins=sensible,qml

Python使

使

{OS} 使OS Linux, Windows, Darwin, FreeBSD, OpenBSD
{Version} Nuitka (0, 6, 14)
{Arch} 使 x86_64, arm64, etc.
{MAIN_DIRECTORY} some_dir/maybe_relative

Python
-O -S Python Nuitka --python-flag=

Python

CCPUgcc使WindowsccacheC使

WindowsgccNuitka ccache.exe使Windows

Nuitka PATH ccache 使 NUITKA_CCACHE_BINARY CI 使

MSVC ClangCL clcache 使Nuitka

CNuitkaappdirs NUITKA_CACHE_DIR 使

python -m nuitka 使 100% Python 使 SyntaxError ImportError Python2Python3使Nuitka Python

C
Windows64Pythonpystone.exeMinGW6420%MSVC MinGW64 使Clang7clang-cl.exe使MSVCMinGW64

Linuxpystone.binclang6gcc-6.3gcc使

C調

CPythonPython DLL使UnicodeDLLDLLPython1DLL

Windows Anaconda Python

Windows 使
DLLNuitka

Windows
WindowsWindows DefenderWindows Indexing ServiceNuitka

Windows
MingGW64MSVCVisual C RuntimeNuitkaDLL

Microsoft Windows 10Microsoftapi-ms-crt-*.dlluclt.dllUniversal C Runtime libraries

Windowswine/ReactOSNuitkaVisual C Runtime

使C

WindowsVisual CCPython
CPython
14.2 2019 3.5, 3.6, 3.7, 3.8, 3.9
14.1 2017 3.5, 3.6, 3.7, 3.8
14.0 2015 3.5, 3.6, 3.7, 3.8
10.0 2010 3.3, 3.4
9.0 2008 2.6, 2.7

WindowsMinGW64CPython
CPython
8.1.0 2015 3.5, 3.6, 3.7, 3.8, 3.9


Nuitka

(constant folding) C

a = 60 * 60 * 24

86400

Nuitka()/

5 + 6 #
not 7 #
5 < 6 #
range(3) #

(使)


__name__ 使

if __name__ == "__main__":
# ...
use_something_not_use_by_program()


使

try:
something()
except ValueError: # ValueError
pass


typelenrangeNuitka

type("string") # str.
len([1, 2]) #
range(3, 9, 2) #
range(3, 9, 0) # (`0`) range

range()

range(100000) #



if __name__ == "__main__":
# ...
use_something_not_use_by_program()


if False:
# ...
use_something_not_use_by_program()





print(side_effect_having() + (1 / 0))
print(something_else())

(1 / 0) ZeroDivisionErro r +

side_effect_having() print() something_else()

Nuitka side_effects 使


try:
b = 8
print(range(3, b, 0))
print("Will not be executed")
except ValueError as e:
print(e)

try b = 8 ValueError try


b = 8
try:
print(range(3, b, 0))
print("Will not be executed")
except ValueError as e:
print(e)


try:
b = 8
print(range(3, b, 0))
print("Will not be executed!")
except ValueError as e:
print(e)

try:
raise ValueError("range() step argument must not be zero")
except ValueError as e:
print(e)


e = ValueError("range() step argument must not be zero")
print(e)


for i in range(1000):
pass

i = 999


if side_effect_free:
pass


a, b, c = 1, side_effect_free(), 3

a = 1
b = side_effect_free()
c = 3



in xrange() in range() 使使

for i in range(1000):
something(i)

range(1000) i

tp_call

def f(a, b, c):
return a, b, c
f(c=get1(), b=get2(), a=get3())

get1() get2() get3()

get1() get2() get3()


for x in [a, b, c]:
something(x)


for x in (a, b, c):
something(x)



Nuitka 使nuitka
Python