Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
提交
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions nuitka-standalone-executable/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# Nuitka: Compile Your Python Code Into a Standalone Executable

Sample code for the Real Python tutorial on compiling Python applications with Nuitka.

## Files

- `wordcount.py`: A small command-line tool that counts the most common words in a text file
- `sample.txt`: Sample text used to test `wordcount.py`
- `cpu_benchmark.py`: A CPU-bound benchmark script used to compare runtime performance across regular Python, `--mode=standalone`, and `--mode=onefile` builds

## Usage

Install Nuitka:

```console
$ python -m pip install nuitka
```

Compile `wordcount.py`:

```console
$ python -m nuitka --mode=standalone wordcount.py
```

Run the compiled executable against `sample.txt`:

```console
$ ./wordcount.dist/wordcount sample.txt -n 5
```
30 changes: 30 additions & 0 deletions nuitka-standalone-executable/cpu_benchmark.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import time


def is_prime(number):
if number < 2:
return False

for divisor in range(2, number):
if number % divisor == 0:
return False

return True


def main():
start = time.perf_counter()

count = 0
for number in range(2, 100_000):
if is_prime(number):
count += 1

elapsed = time.perf_counter() - start

print(f"Primes found: {count}")
print(f"Time: {elapsed:.3f}s")


if __name__ == "__main__":
main()
2 changes: 2 additions & 0 deletions nuitka-standalone-executable/sample.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Python is popular because Python is easy to learn and easy to use.
Python is also popular for data science and automation.
21 changes: 21 additions & 0 deletions nuitka-standalone-executable/wordcount.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
from argparse import ArgumentParser
from collections import Counter
from pathlib import Path


def main():
parser = ArgumentParser(
description="Show the most common words in a text file."
)
parser.add_argument("file", type=Path)
parser.add_argument("-n", "--top", type=int, default=5)
args = parser.parse_args()

words = args.file.read_text(encoding="utf-8").lower().split()

for word, count in Counter(words).most_common(args.top):
print(f"{word}: {count}")


if __name__ == "__main__":
main()
Loading