Community
Fusion API and Scripts
Got a new add-in to share? Need something specialized to be scripted? Ask questions or share what you’ve discovered with the community.
cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

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

13 REPLIES 13
SOLVED
Reply
Message 1 of 14
J.M.MAY
2470 Views, 13 Replies

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

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!

13 REPLIES 13
Message 2 of 14
oafak
in reply to: J.M.MAY

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 14
come.butin
in reply to: J.M.MAY

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 14
mjwootton
in reply to: come.butin

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

Message 5 of 14
come.butin
in reply to: mjwootton

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.
Message 6 of 14
mjwootton
in reply to: come.butin

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.

Message 7 of 14
Jorge_Jaramillo
in reply to: mjwootton

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

 

Message 8 of 14
Jorge_Jaramillo
in reply to: oafak

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 14
mjwootton
in reply to: Jorge_Jaramillo

Thank you. I will experiment with this when I have time again and report back.
Message 10 of 14

#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 14

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

 

 

Message 12 of 14

Robert,

Please let me know if you need more help.

Cheers,
Travis
Message 13 of 14
ryansmith_
in reply to: J.M.MAY

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()))
Message 14 of 14
OceanHydroAU
in reply to: J.M.MAY

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

 

Can't find what you're looking for? Ask the community or share your knowledge.

Post to forums  

Autodesk DevCon in Munich May 28-29th


Autodesk Design & Make Report