# Grashopper Scripting Interface

**URL:** <https://it.discourse.mcneel.com/t/grashopper-scripting-interface/1065>\
**Category:** Scripting e Programmazione\
**Created:** [12 Novembre 2016, 6:55pm UTC](https://it.discourse.mcneel.com/t/grashopper-scripting-interface/1065 "2016-11-12T18:55:30Z")\
**Posts on this page:** 6\
**Page:** 1

<div class="post-metadata">

**Author:** ![emilio](https://sea3.discourse-cdn.com/mcneel/user_avatar/it.discourse.mcneel.com/emilio/32/16095_2.png) [@emilio](https://it.discourse.mcneel.com/u/emilio)\
**Post date:** [12 Novembre 2016, 6:55pm UTC](https://it.discourse.mcneel.com/t/grashopper-scripting-interface/1065/1 "2016-11-12T18:55:30Z")

</div>

Qualcuno la usa ?

Io ho trovato (per caso) questo:

> **[Running Rhino commands in Grasshopper Python](https://discourse.mcneel.com/t/running-rhino-commands-in-grasshopper-python/22380/17)**
>
> @Mr\_Sinter, check out the example below, with the attached DrillHole.gh file. Basically the script does the following: Select a solid brep (eg, a sphere or box) Get the Grasshopper plugin object Open the DrillHole.gh file Pass the id of the brep...

  
e sto provando a capirci qualcosa.

… Ma se trovo un esperto a cui chiedere e’ _molto_ meglio … 😉

Grazie, Ciao

P.S.

ero indeciso sulla categoria.  
‘Ste categorie spesso non funzionano.  
Sarebbe meglio poter settare uno o piu’ tags/categorie, invece di una categoria unica …

---

<div class="post-metadata">

**Author:** ![giuseppe](https://sea3.discourse-cdn.com/mcneel/user_avatar/it.discourse.mcneel.com/giuseppe/32/16416_2.png) [@giuseppe](https://it.discourse.mcneel.com/u/giuseppe)\
**Post date:** [18 Novembre 2016, 8:35am UTC](https://it.discourse.mcneel.com/t/grashopper-scripting-interface/1065/2 "2016-11-18T08:35:24Z")

</div>

Node-in-code  
Concettualmente [questo](https://stevebaer.wordpress.com/2013/12/11/ghpython-node-in-code/)  
e pure [questo](https://stevebaer.wordpress.com/2013/12/12/ghpython-outside-the-canvas/)  
E’ stato riscritto di recente. Con grande merito di Giulio!

---

<div class="post-metadata">

**Author:** ![emilio](https://sea3.discourse-cdn.com/mcneel/user_avatar/it.discourse.mcneel.com/emilio/32/16095_2.png) [@emilio](https://it.discourse.mcneel.com/u/emilio)\
**Post date:** [18 Novembre 2016, 9:58am UTC](https://it.discourse.mcneel.com/t/grashopper-scripting-interface/1065/3 "2016-11-18T09:58:44Z")

</div>

RiCiao !

Se non sbaglio quelli riguardano le possibilita’ degli script Py interni a GH

Io parlavo piu’ di quanto puoi fare da un normale script Py di Rhino per interagire con GH

Non so se c’e’ ( o dov’e’ ) una pagina Web a proposito, anche perche’ mi sembra roba vecchiotta  
Comunque e’ quello spiegato se esegui questo (in Rhino) :

```python
import Rhino

Gh = Rhino.RhinoApp.GetPlugInObject( 'Grasshopper' )
atts = dir( Gh )
for att in atts:
  if not att.startswith( '__' ):
    print( str( help( getattr( Gh, att ) ) ) )

```

Sto provando … quando trovo il tempo … soprattutto grazie ad esempi di Giulio trovati sul Ning GH. 😃

Se combino qualcosa, non manchero’ di rompervi i maroni in questo leggiadro luogo virtuale … 😈

Grazie !

---

<div class="post-metadata">

**Author:** ![emilio](https://sea3.discourse-cdn.com/mcneel/user_avatar/it.discourse.mcneel.com/emilio/32/16095_2.png) [@emilio](https://it.discourse.mcneel.com/u/emilio)\
**Post date:** [21 Novembre 2016, 11:15am UTC](https://it.discourse.mcneel.com/t/grashopper-scripting-interface/1065/4 "2016-11-21T11:15:05Z")

</div>

Ciao !

Prove di interazione tra script e GH:

Ho imbastito una definizione per disegnare una forma ovale (sul piano XY)

[oval.gh](https://mcneelusercontent.s3.amazonaws.com/original/2X/b/b6722d66498dd6e6aeec886311acd0754de41901.gh) (14,9 KB)

Poi c’e’ uno script che consente di impostare raggio e lunghezza della parte rettilinea.  
Inoltre c’e’ un angolo di rotazione per inclinare l’ovale (default: lungo l’asse Y)

A questo punto si seleziona il punto centrale e si possono (dopo aver mostrato l’RCP ) aggiustare i valori con gli slider nell’RCP.  
Ci sono anche due slider per (piccoli) spostamenti

Poi si conferma il Bake (o si rinuncia) da Rhino.  
Tutto qui …

Lo script salva i valori utilizzati per raggio, lato e angolo per usarli come default la prossima volta.

Non so se c’e’ modo di selezionare l’RCP nel pannello come-si-chiama.  
Per cui bisogna andare a cliccare a mano per vederlo … se qualcuno sa come fare, per favore me lo dica.  
Grazie

Ah, ho notato che nell’RCP i valori degli slider non rispettano l’espressione di output impostata …  
Pazienza, speriamo in GH2 ! 🙂

Questo e’ lo script:

```python
import clr
clr.AddReferenceByName( 'Grasshopper' )

import Rhino
import scriptcontext
import rhinoscriptsyntax as rs
import Grasshopper

def getdocdata( key, defval ):
  val = Rhino.RhinoDoc.ActiveDoc.Strings.GetValue( key )
  if not val:
    val = defval
  return val

def setdocdata( key, val ):
  if val: 
    Rhino.RhinoDoc.ActiveDoc.Strings.SetString( key, str( val ) )
    print( 'Stored value: %s = %s' % ( key, str( val ) ) )
  else:
    Rhino.RhinoDoc.ActiveDoc.Strings.Delete( key )

def main():
    rad = float( getdocdata( 'ov-rad', '10' ) )
    sid = float( getdocdata( 'ov-sid', '10' ) )
    deg = float( getdocdata( 'ov-deg', '0' ) )
    while True:
      gep = Rhino.Input.Custom.GetPoint()
      gep.AcceptNothing( True )
      gep.SetCommandPrompt( 'Center of oval ?' )

      radind, radopt = gep.AddOptionDouble( 'Radius',
        Rhino.Input.Custom.OptionDouble( rad ) )
      sidind, sidopt = gep.AddOptionDouble( 'SideLength',
        Rhino.Input.Custom.OptionDouble( sid ) )
      degind, degopt = gep.AddOptionDouble( 'Degrees',
        Rhino.Input.Custom.OptionDouble( deg ) )

      gep.Get()
      res = gep.Result()
      if res == Rhino.Input.GetResult.Cancel:
        return
      elif res == Rhino.Input.GetResult.Nothing:
        setdocdata( 'ov-rad', rad )
        setdocdata( 'ov-sid', sid )
        setdocdata( 'ov-deg', deg )
        return
      elif res == Rhino.Input.GetResult.Option:
        opind = gep.OptionIndex()
        if opind == radind:
          rad = radopt.CurrentValue
        elif opind == sidind:
          sid = sidopt.CurrentValue
        elif opind == degind:
          deg = degopt.CurrentValue
      elif res == Rhino.Input.GetResult.Point:
        cen = gep.Point()
        break

    Gh = Rhino.RhinoApp.GetPlugInObject( 'Grasshopper' )
    if not Gh: 
      return
    
    Gh.LoadEditor()
    Gh.CloseAllDocuments()
# Gh.ShowEditor()

    defn = 'D:\\Rhino\\gh\\oval.gh'

    ok = Gh.OpenDocument( defn )
    if not ok:
      print( 'Unable to load %s' % defn )
      return

    docServer = Grasshopper.GH_InstanceServer.DocumentServer
    doc = docServer[0] # first opened document

    Gh.DisableSolver()
    Gh.HideEditor()

    def FindBatteryByNickname( docObjects, name ):
      if docObjects is None: 
        return None
      for obj in docObjects:
        attr = obj.Attributes
        if attr.PathName == name:
          return obj
      raise Exception( name + ' was not found in document' )

    ghob = FindBatteryByNickname( doc.Objects, 'Center' )
    Gh.AssignDataToParameter( str( ghob.Attributes.InstanceGuid ), cen )

    ghob = FindBatteryByNickname( doc.Objects, 'Radius' )
    Gh.SetSliderRangeAndValue( str( ghob.Attributes.InstanceGuid ), rad,
        ( rad - 10 ) if rad > 10 else 1, 
        rad + 10 )
    ghob = FindBatteryByNickname( doc.Objects, 'Side' )
    Gh.SetSliderRangeAndValue( str( ghob.Attributes.InstanceGuid ), sid,
        ( sid - 10 ) if sid > 10 else 1, 
        sid + 10 )
    ghob = FindBatteryByNickname( doc.Objects, 'Angle' )
    Gh.SetSliderRangeAndValue( str( ghob.Attributes.InstanceGuid ), deg,
        deg - 45, deg + 45 )
    Gh.EnableSolver()

# Gh.RunSolver(True)

    ok = rs.GetString( 
      'Adjust values from the RCP ... Then ... Bake ?', 'Yes', ['No', 'Yes'] )
    if ok and ok[0] in 'yY':
    
      ghob = FindBatteryByNickname( doc.Objects, 'Result' )
      result = Gh.BakeDataInObject( str( ghob.Attributes.InstanceGuid ) )
      if result:
        cu = result[0]
        rs.SelectObject( cu )
      scriptcontext.doc.Views.Redraw()

      ghob = FindBatteryByNickname( doc.Objects, 'Radius' )
      rad = str( ghob.VolatileData[0][0] )
      setdocdata( 'ov-rad', rad )
      ghob = FindBatteryByNickname( doc.Objects, 'Side' )
      sid = str( ghob.VolatileData[0][0] )
      setdocdata( 'ov-sid', sid )
      ghob = FindBatteryByNickname( doc.Objects, 'Angle' )
      deg = str( ghob.VolatileData[0][0] )
      setdocdata( 'ov-deg', deg )

# Gh.CloseDocument()
# Gh.HideEditor()
    
main()

```

Chi volesse provare deve correggere il percorso della definizione nella linea:

```python
    defn = 'D:\\Rhino\\gh\\oval.gh'

```

Ciao !

P.S.

Certo che scriptare GH e’ una cosa piuttosto … esoterica … 😉  
Pare che la documentazione sia un po’ scarsa …  
Per cui spesso si cercano esempi ed istruzioni postati da David, Steve e Giulio (nonche’ da utilizzatori in gamba) sui vari forum … 😃

---

<div class="post-metadata">

**Author:** ![giuseppe](https://sea3.discourse-cdn.com/mcneel/user_avatar/it.discourse.mcneel.com/giuseppe/32/16416_2.png) [@giuseppe](https://it.discourse.mcneel.com/u/giuseppe)\
**Post date:** [21 Novembre 2016, 2:06pm UTC](https://it.discourse.mcneel.com/t/grashopper-scripting-interface/1065/5 "2016-11-21T14:06:26Z")

</div>

Sempre bravissimo Emi.  
Esoterica parecchio…

---

<div class="post-metadata">

**Author:** ![emilio](https://sea3.discourse-cdn.com/mcneel/user_avatar/it.discourse.mcneel.com/emilio/32/16095_2.png) [@emilio](https://it.discourse.mcneel.com/u/emilio)\
**Post date:** [21 Novembre 2016, 2:56pm UTC](https://it.discourse.mcneel.com/t/grashopper-scripting-interface/1065/6 "2016-11-21T14:56:44Z")

</div>

> [@giuseppe](#):
>
> Esoterica parecchio…

Gia’ … ci vorrebbe Sergio. 😃
