def CSVlist(): #prompt the user for a file to import filter = "CSV file (*.csv)|*.csv|*.txt|All Files (*.*)|*.*||" filename = rs.OpenFileName("top_spots", filter) if not filename: return tmplist = list() with open(filename) as csvfile: #with open('top_spots.csv') as csvfile: reader = csv.reader(csvfile) #reader = csv.reader(csvfile, delimiter=',') header_idx = True for row in reader: if header_idx == True: header_idx = False #print(row) continue lat = float(row[0]) long = float(row[1]) alt = float(row[2]) print(lat, long, alt) rs.AddPoint(lat, long, alt) tmplist.append([lat, long, alt]) print(tmplist) b = th.list_to_tree(tmplist) return b
def imageToCircles(): filter = "Text file (*.jpg)|*.jpg|All Files (*.*)|*.*||" filename = rs.OpenFileName("Open Image", filter) if not filename: return image = System.Drawing.Bitmap.FromFile(filename) image.RotateFlip(System.Drawing.RotateFlipType.RotateNoneFlipY) gridScale = image.Width / gridColumns outputX = 0 outputY = 0 imageX = 0 imageY = 0 rs.EnableRedraw(False) for imageX in range (0, image.Width, int(gridScale)): outputX = outputX+gridGapSize outputY = 0 for imageY in range (0, image.Height, int(gridScale)): outputY = outputY + gridGapSize pixel = image.GetPixel(imageX, imageY) diameter = (pixel.GetBrightness()* gridGapSize)* brightnessFactor if (diameter > minCircleSize): if (diameter > maxCircleSize): rs.AddCircle((outputX, outputY, 0), (maxCircleSize/2)) else: rs.AddCircle((outputX, outputY, 0), (diameter/2)) rs.EnableRedraw(True)
def SampleImportNamedViews(): filename = rs.OpenFileName("Open", "Rhino 3D Models (*.3dm)|*.3dm||") if filename: f = Rhino.FileIO.File3dm.Read(filename) if (f.NamedViews.Count > 0): for vi in f.NamedViews: scriptcontext.doc.NamedViews.Add(vi)
def ImportPoints(): #prompt the user for a file to import filter = "Text file (*.txt)|*.txt|All Files (*.*)|*.*||" filename = rs.OpenFileName("Open Point File", filter) if not filename: return #read each line from the file file = open(filename, "r") contents = file.readlines() file.close() # local helper function def __point_from_string(text): items = text.strip("()\n").split(",") center_x = float(items[0]) center_y = float(items[1]) r = float(items[2]) return center_x, center_y, r for entry in contents: if entry != "&\n": info = __point_from_string(entry) center = (info[0], info[1]) radius = info[2] rs.AddCircle(center, radius)
def ImportPoints(): #prompt the user for a file to import filter = "Text file (*.txt)|*.txt|All Files (*.*)|*.*||" filename = rs.OpenFileName("Open Point File", filter) if not filename: return #read each line from the file file = open(filename, "r") contents = file.readlines() file.close() # local helper function def __point_from_string(text): items = text.strip("()\n").split(",") x = float(items[0]) y = float(items[1]) z = float(items[2]) return x, y, z row_contents = list() for line in contents: if line != "&\n": row_contents.append(__point_from_string(line)) else: #rs.AddInterpCurve(row_contents) rs.AddCurve(row_contents) row_contents = list()
def browse_for_file(title=None, folder=None, filter=None): if filter == 'json': filter = 'JSON files (*.json)|*.json||' elif filter == 'obj': filter = 'OBJ files (*.obj)|*.obj||' else: pass return rs.OpenFileName(title, filter=filter, folder=folder)
def on_load_epw(self, sender, e): """Import epw event handler.""" filter = "EPW file (*.epw)|*.epw|All Files (*.*)|*.*||" epw_file = rs.OpenFileName("Open .epw Weather File", filter) # update location data based on epw file self.epw = EPW(epw_file) self.update_location_data() self.draw_sunpath()
def read_file(filename=None): #filename = rs.OpenFileName("Open", "STL(stereolithography) (*.stl)|*.stl||") #filename = '/Users/itq/Desktop/top.nc' if filename is None: filename = rs.OpenFileName("Open", "CarbideMotion (*.nc)|*.nc||") with open(filename, 'r') as f: for line in f: yield remove_return_carriage(line)
def RunCommand(is_interactive): file = rs.OpenFileName(title='Select Sisufile') if not file: return None, Rhino.Commands.Result.Cancel status = link_sisufile(file) if not status: err_message = 'Something went wrong with this sisufile. Try another file' rs.MessageBox(err_message, title='Error', buttons=16) return None, Rhino.Commands.Result.Failure return file, Rhino.Commands.Result.Success
def _get_text_lines_from_drv_file(self): """Prompts for a drv file. Returns its text lines: [drv_text_line, ...] """ filter = "Derivation files (*.drv)|*.drv|All files (*.*)|*.*||" filename = rs.OpenFileName('Open derivation file', filter) if not filename: return file = open(filename, 'r') drv_text_lines = file.readlines() file.close() return drv_text_lines
def EditScriptAtom(): """Edit a Python script in Atom.app.""" file_name = rs.OpenFileName("Open") if file_name is None: None else: atom_app = r"/Applications/Atom.app/Contents/MacOS/Atom" popen("{} {}".format(atom_app, file_name)) rs.Command("_StartAtomEditorListener")
def load_package(self): sys.path.append(self.pluginPath) fileName = rs.OpenFileName(title='Enter or select MW 3D package', filter='MW3D|*.mw3D', extension='mw3D') if fileName is not None: packageFileNames = [] try: fh = open(fileName, 'rb') z = zipfile.ZipFile(fh) for name in z.namelist(): packageFileNames.append(name.split('/')[-1]) outputPath = name.split('/')[:-1] if len(outputPath) == 0: outputPath = [''] packageFolder = fileName.split('\\')[-1].split('.')[0] extractionPath = self.corePath + '\\' + self.cachePath + '\\' + packageFolder + '\\' + outputPath[0] print 'Extracting : ' + packageFolder + '\\' + name if not os.path.isdir(extractionPath): os.mkdir(extractionPath) outfile = open(self.corePath + '\\' + self.cachePath + '\\' + packageFolder + '\\' + name, 'wb') outfile.write(z.read(name)) outfile.close() fh.close() # load buildspace with workpiece and tool path etc. for file in packageFileNames: if file.split('.')[-1] == '3dm': rs.Command(r'_-Open ' + extractionPath + r'/' + file + r' N ' + extractionPath + r'/' + file + r' _Enter') # copy settings to core for file in packageFileNames: if file.split('.')[-1] == 'stl' or file.split('.')[-1] == 'ini' or \ file.split('.')[-1] == 'cl' or file.split('.')[-1] == 'gcode': shutil.copy(extractionPath + '\\' + file, self.corePath + '\\' + file) print 'Adjusting INI File ...' AI = adjustINI.adjustINI(self.pluginPath, self.corePath) AI.adjust_abs_folder() print 'FINISHED' except: print 'ERROR. Could not open MW3D package.'
def OnFileOpenClick(self, sender, e): print "Begin" self.databaseFile = rs.OpenFileName("Open file", "Rhino 3DM Models (*.3dm)|*.3dm||") if self.databaseFile is None: return data = dt.GetLevelsFromAnotherRhinoDoc(self.databaseFile) if data is None: return self.grid.DataStore = data[::-1] self.RegenData() print "End"
def CSVlist(): #prompt the user for a file to import filter = "CSV file (*.csv)|*.csv|*.txt|All Files (*.*)|*.*||" filename = rs.OpenFileName("Open Point File", filter) if not filename: return with open(filename) as csvfile: reader = csv.reader(csvfile) for row in reader: x = float(row[0]) y = float(row[1]) z = float(row[2]) print x, y, z rs.AddPoint(x,y,z)
def _get_text_lines_from_drv_file(self): """Prompts the user for a drv file. Returns: [drv_text_line, ...] [str]. A list of the text lines (without line feeds) making up the drv file. """ filter = "Derivation files (*.drv)|*.drv|All files (*.*)|*.*||" filename = rs.OpenFileName('Open derivation file', filter) if not filename: return file = open(filename, 'r') untrimmed_drv_file_text_lines = file.readlines() file.close() trimmed_drv_file_text_lines = self._trim(untrimmed_drv_file_text_lines) return trimmed_drv_file_text_lines
def _read_shape_file(self): """Prompts for a file. Returns: Shape """ # prompt the user for a file to import filter = "Shape files (*.is)|*.is|All files (*.*)|*.*||" filename = rs.OpenFileName("Open shape file", filter) if not filename: return # read each line from the file file = open(filename, "r") contents = file.readlines() file.close() new_shape = shape.Shape.new_from_is_text_lines(contents) return new_shape
def RunCommand(): fn = rs.OpenFileName(title="select file", filter="Rhino files|*.3dm||") if fn == None: return bitmap = doc.ExtractPreviewImage(fn) f = System.Windows.Forms.Form() f.Height = bitmap.Height f.Width = bitmap.Width pb = System.Windows.Forms.PictureBox() pb.Image = bitmap pb.Height = bitmap.Height #SizeMode = System.Windows.Forms.PictueBoxSizeMode.AutoSize pb.Width = bitmap.Width f.Controls.Add(pb) f.Show()
def _read_rule_file(self): """Prompts for a file. Returns: Rule """ # prompt the user for a file to import filter = "Rule files (*.rul)|*.rul|All files (*.*)|*.*||" filename = rs.OpenFileName("Open rule file", filter) if not filename: return # read each line from the file file = open(filename, "r") contents = file.readlines() file.close() new_rule = r.Rule.new_from_rul_text_lines(contents) return new_rule
def load_image(): filter = "BMP (*.bmp)|*.bmp|PNG (*.png)|*.png|JPG (*.jpg)|*.jpg|All (*.*)|*.*||" #filter = "PNG (*.png)|*.png" filename = rs.OpenFileName("Select image file", filter) if not filename: return # use the System.Drawing.Bitmap class described at # [url]http://msdn.microsoft.com/en-us/library/system.drawing.bitmap.aspx[/url] img = SD.Bitmap(filename) w = img.Width h = img.Height red = [] green = [] blue = [] colourTuple = [] sumR = 0 sumG = 0 sumB = 0 N = 0 for x in range(w): for y in range(h): color = img.GetPixel(x, y) r = rs.ColorRedValue(color) g = rs.ColorGreenValue(color) b = rs.ColorBlueValue(color) red.append(r) green.append(g) blue.append(b) N += N for item in red: sumR += item colourTuple.append(sumR / len(red)) for item in green: sumG += item colourTuple.append(sumG / len(green)) for item in blue: sumB += item colourTuple.append(sumB / len(blue)) print(colourTuple) return colourTuple, filename
def PictureframeOnScale(): filter = "PNG (*.png)|*.png|JPG (*.jpg)|*.jpg|BMP (*.bmp)|*.bmp|All (*.*)|*.*||" #filter = "PNG (*.png)|*.png" filename = rs.OpenFileName("Select existing image file", filter) if not filename: return # use the System.Drawing.Bitmap class described at # [url]http://msdn.microsoft.com/en-us/library/system.drawing.bitmap.aspx[/url] img = SD.Bitmap(filename) img.Dispose # define scale from inch to file unitsystem dblScale = rs.UnitScale(rs.UnitSystem(), 8) #calculate width based on image pixel dimension and image HorizontalResolution w = str((img.Width / img.HorizontalResolution) * dblScale) #release the image (not sure if this is correct but seems to work) # scripted rhino command pictureframe with width and height as calculated above rs.Command("!_-PictureFrame \"" + filename + "\" _Pause " + w + " ")
def read_csv(): filepathname=rs.OpenFileName("File csv for reading", "Text Files (*.csv)|*.csv") if(not filepathname): print("not file path") return """ # get data from user start = rs.GetInteger("Start at line number",1,1) if start is None: print("no start value") return end=rs.GetInteger("End at line number",start,start) if(end is None): print("no end value") return """ start = 0 end = 31 file = open(filepathname) data = [] # line_list = [] for i, line in enumerate(file): if(i < start): continue if(i > end): break #line_list.append(line) string = ''.join( line[:len(line) - 1] ) data.append( string.split(',') ) file.close() # DEBUG # print(data) return data
def importCAD_Button(): try: #Import CAD filePath = rs.OpenFileName("Select CAD to Import", "Autocad (*.dwg)|*.dwg||") if filePath is None: return None rs.EnableRedraw(False) group = rs.AddGroup('Import CAD Group') allImportedObjects = importCAD(filePath) rs.AddObjectsToGroup(allImportedObjects, group) rs.EnableRedraw(True) result = True except: print "Import Failed" result = False try: utils.SaveFunctionData('IO-Import CAD',[result]) except: print "Failed to save function data" return result
def main(): print "Spkcam's vector from gcode" print "selecciona tu archivo de codifo g:" if not rs.IsLayer(LAYER_NAME): rs.AddLayer(LAYER_NAME) else: rs.LayerLocked(LAYER_NAME, locked=False) f_path = rs.OpenFileName(title="Selecciona CodigoG", filter=None, folder=None, filename=None, extension=None) f = open(f_path) gcode = f.readlines() f.close() vector_list, total_time, total_length = vectors_from_gcode(gcode, True) print "Tiempo de corte: %s minutos" % total_time print "Logitud total: %s mm" % total_length rs.LayerLocked(LAYER_NAME, locked=True)
def ImportPoints(): #prompt the user for a file to import filter = "Comma Seperated Values (*.csv)|*.csv|All Files (*.*)|*.*||" filename = rs.OpenFileName("Open Point File", filter) if not filename: return #read each line from the file file = open(filename, "r") contents = file.readlines() file.close() # local helper function def __point_from_string(text): items = text.strip("()\n").split(",") x = float(items[0]) y = float(items[1]) z = float(items[2]) return x, y, z contents = [__point_from_string(line) for line in contents] rs.AddPoints(contents)
def ImportLayersStructure(): """Import layers settings into the current document from a json file.""" file_name = rs.OpenFileName( "Open", "Text Files (*.json)|*.json|All Files (*.*)|*.*||") if not file_name: return with open(file_name, "r") as f: layers_properties = json.load(f) actual_layers_properties = [rs.LayerName(l) for l in rs.LayerNames()] for l, i in zip(layers_properties.keys(), layers_properties.values()): override = True if l in actual_layers_properties: override = rs.MessageBox(l, buttons=1, title="Override existing properties:") if override == 2: override = False else: rs.AddLayer(l) if override: set_layer_properties(l, i)
This component opens the file from a location on your computer. - Provided by Ladybug 0.0.66 Args: _open: Set Boolean to True to browse for a .stat file on your system. Returns: readMe!: ... statFile: The file path of the selected .stat file. """ ghenv.Component.Name = "Ladybug_Open STAT File" ghenv.Component.NickName = 'Open stat file' ghenv.Component.Message = 'VER 0.0.66\nJAN_20_2018' ghenv.Component.IconDisplayMode = ghenv.Component.IconDisplayMode.application ghenv.Component.Category = "Ladybug" ghenv.Component.SubCategory = "0 | Ladybug" #compatibleLBVersion = VER 0.0.59\nFEB_01_2015 try: ghenv.Component.AdditionalHelpFromDocStrings = "4" except: pass import rhinoscriptsyntax as rs if _open == True: filter = "STAT file (*.stat)|*.stat|All Files (*.*)|*.*||" statFile = rs.OpenFileName("Open .stat File", filter) print 'Done!' else: print 'Please set open to True'
Use this component to open an .epw weather file from a location on your computer. - Provided by Ladybug 0.0.63 Args: _open: Set Boolean to True to browse for a weather file on your system. Returns: readMe!: ... epwFile: The file path of the selected epw file. """ ghenv.Component.Name = "Ladybug_Open EPW Weather File" ghenv.Component.NickName = 'Open weather file' ghenv.Component.Message = 'VER 0.0.63\nAUG_10_2016' ghenv.Component.IconDisplayMode = ghenv.Component.IconDisplayMode.application ghenv.Component.Category = "Ladybug" ghenv.Component.SubCategory = "0 | Ladybug" #compatibleLBVersion = VER 0.0.59\nFEB_01_2015 try: ghenv.Component.AdditionalHelpFromDocStrings = "2" except: pass import rhinoscriptsyntax as rs if _open == True: filter = "EPW file (*.epw)|*.epw|All Files (*.*)|*.*||" epwFile = rs.OpenFileName("Open .epw Weather File", filter) print 'Done!' else: print 'Please set open to True'
#Python Workshop Lesson:16 #http://www.designalyze.com/int2pythonscripting16_ImportPtsFromCSV #Import Points from CSV import rhinoscriptsyntax as rs #Select a file to open filename = rs.OpenFileName("Open CSV file", "*.csv|", None, None, None) #open the file for reading file = open(filename, 'r') lines = file.readlines() file.close() #delete the first line because it's a header del lines[0] #print to check the data print(lines) ptNumber = 0 for line in lines: #remove the \n line = line.strip() #split the line by the comma ptInfo = line.split(',') x = float(ptInfo[0]) y = float(ptInfo[1])
if getLayerType(hatch) == "RESIDENTIAL": areasTable[getParent(hatch)][getLayerType(hatch)].append( rs.Area(hatch)) if requestType == True: hatchnames = ["RESIDENTIAL"] outputList = "Level, " + ",".join(hatchnames) + "\n\n" for lev in reversed(outputLevels): max_list = 0 for hlev in hatchnames: if len(areasTable[lev][hlev]) > max_list: max_list = len(areasTable[lev][hlev]) for row in range(max_list): outputList += lev + "," for hname in hatchnames: areasTable[lev][hname] = sorted(areasTable[lev][hname]) try: outputList += str(areasTable[lev][hname][row]) + "," except: outputList += "0," outputList = outputList[:-1] + '\n' if requestType == True: outputList += '\n' print(outputList) ##open file csv_path = rs.OpenFileName() csv_write = open(csv_path, "w") csv_write.write(outputList) csv_write.close() #for key in areasTable: # print(key)
def browse_for_file(title=None, folder=None, filter=None): return rs.OpenFileName(title, filter=filter, folder=folder)