Import file in Python

Hi sorry for simple question, but I spend a lot of time and just can’t do it.

I want to import file “file1.py” from directory d:\directory\ to python script in GH file

I dont know why when I copy my file (file1.py) to the same directory (d:\directory) as my grasshopper.gh file and type
" from file1 import * "
I cannot load file1.py to my python script.

I got error "no module named ‘file1’.

Maybe I dont know where to copy my file?

Assigned to Scripting category

Done it in the end with help of chat GPT :slight_smile:

import sys
#sys.path.append(r’D:\DIR’)
import file1

1 Like

Solution without adding sy.path.append(…) each time

  1. Run this in a Python node inside Grasshopper
import site
sps = site.getsitepackages()

for sp in sps:
    print(sp)

The output should look something like this

  • C:\Users\x\.rhinocode\py39-rh8
  • C:\Users\x\.rhinocode\py39-rh8\lib\site-packages
  1. Find the file named distutils-precedence.pth

Open it with the editor of your choice, where you will find something like

import os; var = 'SETUPTOOLS_USE_DISTUTILS'; enabled = os.environ.get(var, 'stdlib') == 'local'; enabled and __import__('_distutils_hack').add_shim();
  1. Add this in the next line
import sys; sys.path.append(r"D:\proton\My files\grasshopper\python")
  1. Restart Rhino and verify
import sys
paths = sys.path

for path in paths:
    print(path)
  1. Add your *.py Files

  1. Enjoy

1 Like

@dn.aur Thank you so much for documenting this technique!

Just a small note, if you want to actively develop the referenced python modules you’ll need to reload the module, like so:

import myExternalPythonFile

from importlib import reload 
reload(myExternalPythonFile)
1 Like

This also may work for you?

1 Like