How to use modules like numpy, scipy etc. by conda in Fusion 360 scripts?

How to use modules like numpy, scipy etc. by conda in Fusion 360 scripts?

J.M.MAY
Explorer Explorer
5,745 Views
14 Replies
Message 1 of 15

How to use modules like numpy, scipy etc. by conda in Fusion 360 scripts?

J.M.MAY
Explorer
Explorer

Hi!

 

I want to write a script in Python and in the Visual Studio Code editor using modules like numpy. If I simply add the line "import numpy as np" to my script without further actions, numpy is not recognized. How can I refer to the installation of anaconda on my PC, because with anaconda, numpy and other useful modules would be available?

 

Thanks in advance for your answer!

Accepted solutions (1)
5,746 Views
14 Replies
Replies (14)
Message 2 of 15

oafak
Enthusiast
Enthusiast
Accepted solution

It is interesting to note that most users simply ignored the question. Could it be that it is considered unnecessary to call on other libraries in conjunction with the Fusion 360 API? I find that in my own work, it makes some things easier for me to use numpy, matplotlib and some other modules. Please note that the experience here only applies to Windows 10. 

From Anaconda, you can easily request a terminal from which your Python interpreter is reachable. In the Python version installed into Fusion 360, things are different. The real problem is to locate where the Fusion 360 embedded Python interpreter is located. Searching manually on my computer, I found it at:

c:\Users\myUserID\AppData\Local\Autodesk\Webdeploy\Production\abxy234...

That last subdirectory appears to be a 40 character random generate alphanumeric. 

My initial fear stems from the fact that that last directory appears to change frequently and I therefore wonder if changes made will be permanent. I have tried it and so far, it works.

Once you move to that directory when launching 

pip install numpy

or any other desired library, it works with the Python interpreter in Fusion 360.

 

Message 3 of 15

come.butin
Explorer
Explorer

As mentionned by @oafak, a solution is to install libraries with pip from the Python path used by Fusion360.

Here is a script that you can execute through Fusion360 on Windows, that find the right path and install numpy and scipy automatically.

 

 

import adsk.core, adsk.fusion, adsk.cam, traceback
import os, sys

def run(context):
    ui = None
    try:
        app = adsk.core.Application.get()
        ui  = app.userInterface

        install_numpy = sys.path[0] +'\Python\python.exe -m pip install numpy'
        install_scipy = sys.path[0] +'\Python\python.exe -m pip install scipy'

        os.system('cmd /c "' + install_numpy + '"')
        os.system('cmd /c "' + install_scipy + '"')
        
        try:
            import scipy
            ui.messageBox("Installation succeeded !")
        except:
            ui.messageBox("Failed when executing 'import scipy'")

    except:
        if ui:
            ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))

 

Message 4 of 15

mjwootton
Explorer
Explorer

Thank you. This solution is fantastic. Do you know how to adapt it for macOS? I'd be very grateful for any help.

0 Likes
Message 5 of 15

come.butin
Explorer
Explorer
I'm not familiar with MacOS. Although, I think that the only things you have to adapt is the command line which is executed on your terminal (the arguments of os.system() function).
The current function is getting the current path of Fusion (sys.path), and execute the corresponding Python.exe from th terminal with the "pip install" option to install your libraries.
Feel free to post if you find a solution.
0 Likes
Message 6 of 15

mjwootton
Explorer
Explorer

I spent a long time yesterday trying different variations of os.system(...) and other methods, but didn't manage to get anywhere. There's something odd going on with the version of Python in the macOS version of Fusion 360. Even when I got it to run Pip installations, it still wasn't able to import the relevant module.

 

I'll update this thread if I find a solution.

0 Likes
Message 7 of 15

Jorge_Jaramillo
Collaborator
Collaborator

Hi,

I posted yesterday a solution on this topic to use pandas.

You can use the step by step to load any other module you need (change module names on step #5).

If you are working on mac you might need to change step #4 to:

source py39_fusion\Scripts\activate

 

Hope this could work for you.

 

Regards,

Jorge

 

0 Likes
Message 8 of 15

Jorge_Jaramillo
Collaborator
Collaborator
You can always know where Fusion360's Python interpreter is with:
(from Text Command (Ctlr-Alt-C) and set it to "Py" on right hand bottom corner):
import sys
print(sys.executable)
Message 9 of 15

mjwootton
Explorer
Explorer
Thank you. I will experiment with this when I have time again and report back.
0 Likes
Message 10 of 15

travis.eubanks9584H
Observer
Observer
#This version worked for me. I had to modify the original script as my Fusion360 path was not being called correctly.
 
import adsk.core, adsk.fusion, adsk.cam, traceback
import subprocess, sys

def run(context):
    ui = None
    try:
        app = adsk.core.Application.get()
        ui  = app.userInterface

        try:
            subprocess.check_call([sys.path[0] + '\Python\python.exe', "-m", "pip", "install", 'scipy'])
            subprocess.check_call([sys.path[0] + '\Python\python.exe', "-m", "pip", "install", 'numpy'])
            ui.messageBox("Packages installed.")
        except:
            ui.messageBox("Failed to install packages.")

        try:
            import scipy
            import numpy as np
            ui.messageBox("Import succeeded!")
        except:
            ui.messageBox("Failed when importing packages.")

    except:
        if ui:
            ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))
Message 11 of 15

RA_Nouveau
Enthusiast
Enthusiast

Thank you all. I tried this a few months ago and got nowhere.

 

 

0 Likes
Message 12 of 15

travis.eubanks9584H
Observer
Observer
Robert,

Please let me know if you need more help.

Cheers,
Travis
0 Likes
Message 13 of 15

ryansmith_
Contributor
Contributor

This version works for me but only in a Script. It crashes Fusion when it's run from an Add-In. I'd like to be able to automatically re-install after a Fusion update that removes the package.

 

import adsk.core, adsk.fusion, adsk.cam, traceback
import subprocess, sys

def run(context):
    ui = None
    try:
        app = adsk.core.Application.get()
        ui  = app.userInterface
        ui.messageBox('About to install pyserial')
        subprocess.check_call([sys.executable, '-m', 'pip', 'install', 'pyserial'])
        ui.messageBox('Pyserial has been installed')

    except:
        if ui:
            ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))
0 Likes
Message 14 of 15

OceanHydroAU
Collaborator
Collaborator

The correct way is to create a ./lib folder inside your add-in, get the package, extract it, then tell your add-in to use it:-

 

 

pip download numpy --python-version 3.11 --platform win_amd64 --only-binary=:all:
pip download numpy --python-version 3.11 --platform manylinux2014_x86_64 --only-binary=:all:
pip download numpy --python-version 3.11 --platform macosx_10_9_x86_64 --only-binary=:all:
pip download numpy --python-version 3.11 --platform macosx_11_0_arm64 --only-binary=:all:
   
unzip numpy-1.26.4-cp311-cp311-win_amd64.whl -d windows
unzip numpy-1.26.4-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl -d linux
unzip numpy-1.26.4-cp311-cp311-macosx_10_9_x86_64.whl -d mac_intel
unzip numpy-1.26.4-cp311-cp311-macosx_11_0_arm64.whl -d mac_arm

 

 

(Fusion uses python 3.11 as at time of writing)

 

 

import sys
import os
import platform

script_dir = os.path.dirname(__file__)

# Check the operating system and architecture
if sys.platform.startswith('linux'):
    lib_dir = os.path.join(script_dir, 'lib', 'linux')
elif sys.platform == 'win32':
    lib_dir = os.path.join(script_dir, 'lib', 'windows')
elif sys.platform == 'darwin':
    # Distinguish between Intel and ARM on macOS
    if platform.machine().startswith('arm') or platform.machine().startswith('aarch64'):
        lib_dir = os.path.join(script_dir, 'lib', 'mac_arm')
    else:
        lib_dir = os.path.join(script_dir, 'lib', 'mac_intel')
else:
    raise Exception("Unsupported OS")

if lib_dir not in sys.path:
    sys.path.append(lib_dir)

import numpy as np

 

 

numpy is a pretty heavy package... you might want to see if there's a way to defer loading it until you need it - on my crazy-fast machine, it takes 3 seconds

 

Message 15 of 15

OceanHydroAU
Collaborator
Collaborator

Update: this looks like the correct way to defer loading of python modules until needed (because otherwise numpy slows down the opening of Fusion a lot, which is against Autodesk add-in rules).

 

def your_addin_command():
    import numpy as np
    # other imports
    # your code here...