Skip to content

Instantly share code, notes, and snippets.

@thekaushikls
Last active January 10, 2025 15:31
Show Gist options
  • Save thekaushikls/58a0727a86fb2e74121a782e123d163e to your computer and use it in GitHub Desktop.
Save thekaushikls/58a0727a86fb2e74121a782e123d163e to your computer and use it in GitHub Desktop.
compile .py to .dll
#!/usr/bin/env ipy
# -*- coding: utf-8 -*-
"""
This script collects all python scripts (.py) from the project (including sub-folders) and compiles them into a dynamic link library (.dll) file. File will be placed inside the 'bin' folder. Place this file in the root directory of a project, prior to execution.
Note:
This script uses the Common Language Runtime Library (CLR). Use IronPython for execution.
Download IronPython 2.7.9 from https://github.com/IronLanguages/ironpython2/releases/tag/ipy-2.7.9
Usage:
build_module.py
Author:
Kaushik LS - 18.08.2022
Source:
https://gist.github.com/thekaushikls/58a0727a86fb2e74121a782e123d163e
License:
MIT License
Copyright (c) 2022 Kaushik LS
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
# - - - - - - - - IN-BUILT IMPORTS
import os
from traceback import format_exc
from shutil import copy2
# - - - - - - - - CLASS LIBRARY
class Compiler:
@staticmethod
def collect_files(folder_path):
"""Collects relevant python script files.
Args:
folder_path (str): Root directory to collect_files.
Returns:
list(str): List of absolute file paths.
"""
files = []
# Ignore the current file, and files named '__init__.py'. Add other names if required.
ignore_list = (os.path.basename(__file__), "__init__.py", "local", "bin")
if os.path.isdir(folder_path):
for file in os.listdir(folder_path):
abs_path = os.path.join(folder_path, file)
# ignore from ignore_list.
if not file in ignore_list and file.endswith(".py"):
files.append(abs_path)
# Recursiion for sub-folders
elif os.path.isdir(abs_path) and file.lower() not in ignore_list:
files += Compiler.collect_files(abs_path)
return files
@staticmethod
def Build(filename, source_folder = "", copy_target = "", export_folder = "bin"):
"""Collects and compiles project files into a dll.
Args:
filename (str): Name of final output (.dll) file.
source_folder (str): (optional) Folder to collect files from.
copy_target (str) : (optional) File path to where the output needs to be copied.
export_folder (str): Subfolder for output file.
Returns:
(bool) True if successful, False otherwise.
"""
folder_name = os.path.dirname(os.path.abspath(__file__))
source_folder = os.path.join(folder_name, source_folder)
target_folder = os.path.join(folder_name, export_folder)
target_file = os.path.join(target_folder, filename)
# Create export folder.
if not os.path.exists(target_folder):
os.makedirs(target_folder)
# Collect necessary files from project folder.
program_files = Compiler.collect_files(source_folder)
try:
from clr import CompileModules
CompileModules(target_file, *program_files)
print("\nBUILD SUCCESSFUL\nTarget: {}\n".format(target_file))
# Copy output file to user specified location.
if copy_target and os.path.exists(copy_target):
copy2(target_file, copy_target)
print("COPY SUCCESSFUL\n")
return True
except ImportError:
print("\nBUILD FAILED\n\nPlease run the script using IronPython.\nRefer docstrings for more information.\n")
except Exception as ex:
print("\nBUILD FAILED\n")
print(format_exc())
print(str(ex))
return False
# - - - - - - - - RUN SCRIPT
def Run():
Compiler.Build("my_module.dll")
if __name__ == "__main__":
Run()
@Bang1338
Copy link

Problem: The code must be Python 2, while we're moved to Python 3.

Question: Does it require IronPython installed to use DLL? If so, then you should remove this gist to avoid misleading let them add the library then compile into DLL, not "I have to install IronPython in my machine to use that DLL"

@thekaushikls
Copy link
Author

thekaushikls commented Sep 3, 2024

@Bang1338 thank you for your comment. There are a few reasons why this script is as it is.

  1. Rhino still used IronPython v2.12 (AFAIK, or at least when I first wrote this script). The shebang at the top indicates the usage of ipy or IronPython for this purpose.
  2. The compiled binary can only be used via IronPython. I haven't personally tested using it in IronPython3 although it might be possible.
  3. The compiled binary (if renamed from plugin.dll to plugin.ghpy Grasshopper should load it automatically. Although note that the SDK mode previously available via the GhPython component might no longer be available in the newer scripting components.
  4. If you still want to use the script, maybe to compile CPython code into an IronPython binary, kindly use this GitHub Action that I have created. Link: https://github.com/marketplace/actions/make-ghpy

Note: If you require a managed binary (dll) as output, it is cleaner to create one with Visual C#. Such an output can be used inside other C# projects, CPython projects, and IronPython projects.

Good Luck!

Best,
Kaushik

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment