How to install Python modules in Dynamo Core Runtime 2.8.0?

Nice, i think need improve some setting from dynamo core to can do that.

2 Likes

@chuongmep well, works for a lot of packages but open3d threw an error after installign it like that, see Cpython 3.8.3 open3d dll import error - Developers - Dynamo (dynamobim.com)

any thoughts?

1 Like

I have suggest change to py -3.x -m ..... to install if user have mutiple version python installed in computer.

3 Likes

Great toturial, easy to follow! Got it working within 15 minutes

3 Likes

@chuongmep @solamour

I was reading through the guide you put together for connecting python modules to dynamo with Cpython3.

I’m trying to use the Anaconda method described by Sol so that i can use the scikit-geometry module.

many packages installed with Anaconda are recognized by dynamo, such as numpy, scipy, pandas.

# Load the Python Standard and DesignScript Libraries
import sys
import clr
clr.AddReference('ProtoGeometry')
from Autodesk.DesignScript.Geometry import *

sys.path.append(r'C:\ProgramData\Anaconda3\envs\Dynamo212\Lib\site-packages')

import numpy
import scipy
import pandas
import matplotlib


# The inputs to this node will be stored as a list in the IN variables.
dataEnteringNode = IN

# Place your code below this line

# Assign your output to the OUT variable.
OUT = sys.path,sys.version, sys.executable

but when i add matplotlib, i get an unexpected error

Warning: ImportError : DLL load failed while importing ft2font: The specified module could not be found. [’ File “”, line 12, in \n’, ’ File “C:\ProgramData\Anaconda3\envs\Dynamo212\Lib\site-packages\matplotlib\init.py”, line 207, in \n _check_versions()\n’, ’ File “C:\ProgramData\Anaconda3\envs\Dynamo212\Lib\site-packages\matplotlib\init.py”, line 192, in _check_versions\n from . import ft2font\n’]

when i check this in python in the terminal or in VSCode, the modules matplotlib and skgeom load with no issue


stackoverflow suggest this has something to do with the specific version of matplotlib, but @chuongmep seems to have been able to import it successfully without needing to restrict the version, and as stated above, the modules load when running in the Anaconda environment.

I’m pretty sure i built the Anaconda environment from Dynamo’s embedded python, but there’s clearly something different between what gets configured inside dynamo, and the Anaconda environment.

if i open the dynamo embedded python environment (?) and enter the same procedures as in dynamo, the outcome is reproducible

i’m not sure what is different. both are using python 3.8.3

edit - i guess there are vague instructions to install CGAL directly, and then build scikit-geometry

from the article:

i will try this tomorrow

You can try to fix by some solution in this, I don’t recommend use Anaconda to install package.
python - from matplotlib import ft2font: “ImportError: DLL load failed: The specified procedure could not be found.” - Stack Overflow

1 Like

i guess i’m interested to try and understand what’s different between dynamo’s Embedded Python and what gets configured in the Anaconda environment. It’s a shame it doesn’t work as expected because Anaconda seems like a really nice way to manage packages.

but, yeah, to ‘fix’ it, i’ll try to install matplotlib directly to the Embedded Python with the get-pip method

Hi @mclough - From our side, we essentially embedded Python into the Dynamo ecosystem using this process: Python embeddable zip: install Tkinter - Stack Overflow, which may contain the nuggets you are looking for :slight_smile:

Unfortunately, I do not know why the Anaconda and direct install versions may be different, but it’s worth a read of the above if you are curious.

1 Like

Hi Solamor

Just read your guide to acess requests package for Python in Dynamo.
This guide helped me alot!

Thanks alot.

1 Like

You are most welcome @Mainot :slight_smile: Glad it helped!

1 Like

Hi, I have this warning and don’t know how to solve it.


Could you please tell me what could theoretically be wrong? I installed Python 3.10.8 recently for educational purposes. Do you think it could be problem?

Hi,
the error says the path of pthFilePath is wrong.
You don’t need to install Python3.10, Dynamo use a internal CPython3 engine

hello,
here an updated code

image


# More info here
# https://github-wiki-see.page/m/DynamoDS/Dynamo/wiki/Customizing-Dynamo%27s-Python-3-installation
import sys
import clr
import System
import re
print('\n'.join(sys.path))
pyEngineName = sys.implementation.name 

clr.AddReference("System.Windows.Forms")
import System.Windows.Forms
from System.Windows.Forms import MessageBox, MessageBoxButtons, MessageBoxIcon

from System.Reflection import Assembly
dynamo = Assembly.Load('DynamoCore')
dynamo_version = str(dynamo.GetName().Version)
dynamo_version = tuple(int(x) for x in dynamo_version.split("."))
print('dynamo_version', dynamo_version)
init_setup = False
if pyEngineName != "ironpython" and dynamo_version > (2,8,0,0):
    #reDir = System.IO.DirectoryInfo(re.__file__)
    #path_py3_lib = reDir.Parent.Parent.FullName
    clr.AddReference('Python.Included')
    import Python.Included as pyInc
    path_py3_lib = pyInc.Installer.EmbeddedPythonHome
    #sys.path.append(path_py3_lib + r'\Lib\site-packages')
    import platform, os, subprocess, importlib.util
    from System import Environment
    from System.Net import WebClient
    #
    # get paths
    assert os.path.isdir(path_py3_lib)
    pipDirPath = os.path.join(path_py3_lib, 'Scripts')
    pipfilePath = pipDirPath + "\\pip"
    get_pip_path = os.path.join(path_py3_lib, 'get-pip.py')
    site_packagepath = os.path.join(path_py3_lib, 'Lib\site-packages')
    #assert os.path.isdir(site_packagepath), "Error folder  {} not found".format(site_packagepath)
    #
    if not os.path.isfile(get_pip_path):
        client = WebClient()
        client.DownloadFile('https://bootstrap.pypa.io/get-pip.py', get_pip_path)
    filepy_pth = f'python{sys.version_info.major}{sys.version_info.minor}._pth'
    pthFilePath = os.path.join(path_py3_lib, filepy_pth)
    assert os.path.isfile(pthFilePath), "Error file {} not found".format(pthFilePath)
    
    with open(pthFilePath, 'r+') as f:
        lines = f.readlines()
        if re.match(r'#import site', lines[-1]) is not None:
            lines[-1] = re.sub(r'#', '', lines[-1])
            f.writelines(lines)
    
    if not os.path.isdir(pipDirPath):
        #print(f'installing pip in local Python environment: {path_py3_lib}')
        print('installing pip in local Python environment: {}'.format(path_py3_lib))
        subprocess.Popen(["python", get_pip_path])
        # try to update pip
        try:
            #subprocess.run(['python', '-m', pipfilePath, 'install', '--upgrade pip'],  cwd = path_py3_lib)
            subprocess.Popen(["python", '-m', pipfilePath, 'install', '--upgrade pip'],  cwd = path_py3_lib)
        except Exception as ex:
            print(str(ex))
        init_setup = True
        MessageBox.Show("Initialization in Progress...\nWhen installation finished, close Dynamo and relaunch this script to install packages", "Initialization In Progress...", MessageBoxButtons.OK, MessageBoxIcon.Warning)
        raise Exception("close Dynamo and relaunch this script to install packages")
    else: 
        print('pip was already installed for this local Python environment')
        init_setup = False
    #
    installPackages = IN[0]
    if installPackages and not init_setup:
        sys.path.append(site_packagepath)
        for packageName in installPackages:
            spec = importlib.util.find_spec( packageName )
            if spec is None: 
                try:
                    subprocess.run([pipfilePath, 'install', '--target='+ site_packagepath, packageName], cwd = path_py3_lib)
                    print('{} succesfully installed'.format(packageName))
                except Exception as ex:
                    #print(f'error while installing {packageName}')
                    print('error while installing {}'.format(packageName))
                    print(str(ex))
            else:
                #print(f"package {packageName} is already installed")
                print("package {} is already installed".format(packageName))
                
        # check result
        if False:
            import numpy as np
            import pandas as pd
        MessageBox.Show("Python installation and configuration completed successfully!", "Installation Python", MessageBoxButtons.OK, MessageBoxIcon.Information)
    
elif pyEngineName == "ironpython" and dynamo_version > (2,8,0,0):
    MessageBox.Show("Switch to CPython3 then relaunch the script!", "Installation Python", MessageBoxButtons.OK, MessageBoxIcon.Warning)
    
else:
    MessageBox.Show("Python installation and configuration completed successfully!", "Installation Python", MessageBoxButtons.OK, MessageBoxIcon.Information)
12 Likes

Hello @c.poupin , I have this warning

1 Like

Hi,
I fixed the code yesterday (little change), try my last code or change IN[1] to IN[0]

5 Likes

Wow, it works nice after change to IN[0] for numpy, pandas and also for shapely :slight_smile:
Thank you very much.

2 Likes

Helo,

I am getting the following error:
Could you help me out please?

edit: second attempt, worked. thanks

1 Like

Good afternoon!
Can you tell me how to install the module openpyxl in Dynamo’s Python?

Hello @maksim7747 have you tried this yet? Customizing Dynamo's Python 3 installation · DynamoDS/Dynamo Wiki · GitHub

Also, if you have Revit 2024.2 you will halve it now out of the box :star_struck:

2 Likes

Добрый день! Да я пробовал это способ. Пункты 18,19,20 не выполняются.

Translation: Good afternoon Yes, I tried this method. Points 18,19,20 are not fulfilled.