Create a Pyd File in Python
Last Updated :
13 Feb, 2024
A Pyd file, also known as a Python Dynamic Module, is a compiled Python extension module with the .pyd
extension. It is equivalent to a DLL (Dynamic Link Library) on Windows and a shared library on other platforms. Pyd files contain compiled Python code, allowing you to create high-performance extensions for your Python programs. In this article, we’ll explore the process of creating a Pyd file step by step.
How To Create A Pyd File In Python?
Below, is the step-by-step guide for How To Create A Pyd File In Python.
Step 1: Create a Virtual Environment
First, create the virtual environment using the below commands
python -m venv env
.\env\Scripts\activate.ps1
Step 2: Write the Python Code
Let’s start by creating a simple Python script that we want to compile into a Pyd file. For this example, let’s create a file named example_module.py
with the following content:
Python3
def greet(name):
return f "Hello, {name}!"
|
Step 3: Create a Setup File
To compile the Python script into a Pyd file, we need to create a setup file. Create a file named setup.py
with the following content:
The setup.py
file specifies the name of the module (example_module
) and the source file (example_module.c
). The source file will be generated in the next step.
Python3
from setuptools import setup, Extension
setup(
name = 'example_module' ,
ext_modules = [
Extension(
'example_module' ,
sources = [ 'example_module.c' ],
)
],
)
|
Step 4: Generate the C Source File
To generate the C source file from the Python script, open a terminal or command prompt and run the following command:
cythonize -i example_module.py
This command uses cython, a programming language that makes it easy to write C extensions for Python, to generate the C source file (example_module.c
) and compile it.
Step 5: Build the Pyd File
Now, run the following command to build the Pyd file:
python setup.py build_ext --inplace
This command uses the setup.py
script to build the extension module. The --inplace
option ensures that the compiled Pyd file is placed in the same directory as the source files.
Step 6: Test the Pyd File
You can now test the created Pyd file by importing it in a Python script or interactive session. Create a file named test_example_module.py
with the following content:
Python3
import example_module
result = example_module.greet( "World" )
print (result)
|
Run the script using:
python test_example_module.py
If everything is set up correctly, you should see the output:
Output
Hello, World!
Video Demonstration
Congratulations! You have successfully created and tested a Pyd file in Python. This process can be extended to more complex modules, and the resulting Pyd files can be distributed and used like regular Python modules.
Share your thoughts in the comments
Please Login to comment...