如何打包多個Python模組?


處理執行數千行程式碼的複雜程式會產生兩個基本問題:管理程式碼以瞭解在何處實現了哪些功能,以及在發生錯誤時除錯程式。幸運的是,這兩個問題都可以透過將程式碼分解成多個模組,然後從不同的模組建立一個單個指令碼檔案來解決。

Python 提供了這種精確的功能,其中不同的 Python 模組可以打包到單個可執行指令碼中。此功能允許輕鬆管理和除錯複雜的程式。

使用zip

打包 Python 中多個模組的一種方法是,從不同的模組建立一個 zip 檔案,然後在 Python 終端中執行該 zip 檔案。要使用此方法,第一步是定義不同的模組,確保其中一個模組命名為 main.py,這允許編譯器知道程式執行將從哪裡開始。

然後應將模組壓縮成單個檔案,然後可以執行該檔案以獲得輸出。

語法

以下是 Python 中執行 zip 檔案的語法:

python file_name.zip

示例

在此示例中,第一步是定義 main.py 模組,該模組從 sum_fibonacci 模組匯入斐波那契函式並將值 10 傳遞給該函式。

from sum_fibonacci import fibonacci output = fibonacci(10) print(output)

sum_fibonacci 模組中定義的斐波那契函式用於計算斐波那契數列中前 10 個數字的和,並將該值返回到主模組。

def fibonacci(term): first_val = 0 second_val = 1 sum_fibonacci = 0 for num in range(0, term): sum_fibonacci = sum_fibonacci + first_val next_val = first_val + second_val first_val = second_val second_val = next_val return sum_fibonacci

然後將 main 模組和 sum_fibonacci 模組壓縮到 fibonacci.zip 中,然後可以使用下面的程式碼執行它以獲得所需的輸出。

python fibonacci.zip

輸出

輸出結果為斐波那契數列中前 10 個數字的和。

88

使用stickytape

打包 Python 中多個模組的另一種方法是使用 stickytape 命令。要使用 stickytape,第一步是定義需要打包的不同模組,其中一個模組應該命名為 main.py,因為執行從此模組開始。

定義所有模組後,可以使用 Python shell 中的 stickytape 命令在主模組上自動建立一個單個指令碼檔案,該檔案可以執行以獲得程式碼的輸出。

語法

以下是使用 stickytape 建立單個檔案的語法:

stickytape main.py > output_file_name.py

示例

第一步是從程式執行開始的地方定義 main.py 模組。main 模組匯入其他模組的成員,並用於呼叫這些成員。

# Importing the members of the modules from calculate import Calculation from fact_find import factorial # Calling method of Calculation class in calculate module calc = Calculation(value=5) # Calling the factorial function in fact_find module output = factorial(calc.value) print(output)

接下來定義 calculate.py 模組中的 Calculation 類,以接收來自 main 模組的值並將其分配給 self.value 物件。

class Calculation: def __init__(self, value): self.value = value # assigning 5 as value

然後定義 fact_find 模組中的 Factorial 函式,以遞迴地計算 5 的階乘。

factorial(fact): if fact == 1: return fact else: return fact*factorial(fact-1) # recursive function to find factorial

最後,使用 stickytape 將所有模組捆綁到 calculate_factorial.py 中,然後可以執行它以獲得程式的輸出。

# Creating a single file which bundles all the modules stickytape main.py > calculate_factorial.py

輸出

輸出結果是 5 的階乘。

120

更新於:2022年11月23日

2K+ 瀏覽量

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.