python:模块化程序

打包

使用PyInstaller来打包Python脚本(如main.pycalculator_module.py)可以将其转换为独立的可执行文件exe

  1. 安装PyInstaller
    首先,你需要确保已经安装了PyInstaller。如果没有安装,可以使用pip进行安装:

    1
    pip install pyinstaller
  2. 准备脚本
    确保你的main.pycalculator_module.py在同一个目录下,并且main.py正确地导入了calculator_module.py。例如,在main.py中:

    1
    import calculator_module
  3. 使用PyInstaller打包
    打开命令行或终端,导航到包含你的Python脚本的目录,然后运行以下命令:

    1
    pyinstaller --onefile main.py

    这里,--onefile选项告诉PyInstaller将所有内容打包到一个单独的可执行文件中。

  4. 生成的可执行文件
    运行上述命令后,PyInstaller将开始处理你的脚本并生成一个dist目录,其中包含一个名为main(在Windows上是main.exe,在macOS上是main,在Linux上是mainmain.bin,具体取决于系统)的可执行文件。

  5. 运行可执行文件
    你可以直接在命令行或双击(取决于操作系统)来运行生成的可执行文件。

注意事项

  • 隐藏导入:如果你的脚本使用了动态导入或某些库以非标准方式导入模块,你可能需要在PyInstaller的spec文件中手动添加这些隐藏导入。
  • 依赖项:确保所有脚本依赖的第三方库都已安装,并且可以通过pip list查看。

main.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import calculator_module as cm

def main():
try:
while True:
print("Simple Calculator")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
print("5. Exit")

choice = input("Enter your choice (1/2/3/4/5): ")

if choice == '5':
print("Exiting the calculator.")
break

try:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))

if choice == '1':
result = cm.add(num1, num2)
print(f"The result is {result}")
elif choice == '2':
result = cm.subtract(num1, num2)
print(f"The result is {result}")
elif choice == '3':
result = cm.multiply(num1, num2)
print(f"The result is {result}")
elif choice == '4':
result = cm.divide(num1, num2)
print(f"The result is {result}")
else:
print("Invalid choice. Please try again.")
except ValueError as ve:
print(f"Value Error: {ve}")

except Exception as e:
print(f"An unexpected error occurred: {e}")

if __name__ == "__main__":
main()

calculator_module.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# calculator_module.py

def add(a, b):
"""返回两个数的和"""
return a + b

def subtract(a, b):
"""返回两个数的差"""
return a - b

def multiply(a, b):
"""返回两个数的积"""
return a * b

def divide(a, b):
"""返回两个数的商,如果除数为0则抛出异常"""
if b == 0:
return("除数不能为零")
return a / b

貌似这与库的差不多

Donate
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
  • Copyrights © 2023-2025 John Doe
  • Visitors: | Views:

请我喝杯茶吧~

支付宝
微信