Compile the Python program into a dynamic library pyd file (that is, encrypt the py file)

Table of contents

1. Write a piece of Python code

2. Prepare the compilation environment

3. Start compiling

4. Call (take Windows system as an example)


1. Write a piece of Python code

  • First type a piece of code, here write a simple function to find the sum of two numbers in the Python file named data.py , the function name is i_sum ;
  • One thing to note is that in addition to the common content in the first two lines of the code, add  # cython: language_level=3 to the third line to compile in the Python3 environment.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# cython: language_level=3

"""
@File    :   data.py
@Time    :   2023-07-16 16:10:52
"""

# here put the import lib
import os

def i_sum(a, b):
	# 计算两数之和
	c = a + b
	return c

2. Prepare the compilation environment

Compile under Windows system:

pip install easycython

3. Start compiling

Compile under Windows system:

  • Open the command line program of the Windows system, enter the folder of the data.py program (mine is placed in the root directory of the D drive), and use the command:
easycython data.py

If the following error occurs, you need to install Microsoft Visual C++ 

We need to download Microsoft Visual C++ 14.0, address: download . Choose to install (Windows 10 SDK can not be installed)

If the error is still reported, delete the files in the installation directory and install as follows.

After the installation is complete, run the command again to compile successfully.

  • At this time, the folder where  the data.py program is located has the following files, and the .pyd file is renamed to data.pyd (among them, cp38 indicates that the applicable Python version is 3.8, and win_amd64 indicates that the applicable Python bit number is 64 bits, and attention should be paid when calling) , other files can be deleted:

4. Call (take Windows system as an example)

Directly import the library to use when typing code:

  • Command line operation demonstration : Open the command line program of the Windows system, enter the path where the data.pyd file is located (mine is in the root directory of the D drive), and enter the Python environment. Data can then be called as a Python library.

  • In this way, the Python file is compiled into a dynamic link library for Windows and Linux, which can be used perfectly.

  • Note : You need to pay attention to the Python version when calling, and the calling environment must be consistent with the version of the compiled Python environment (such as Python3.8.10 compilation, just call it in the Python3.8 environment).

Guess you like

Origin blog.csdn.net/qq_45100200/article/details/131750945