def get_xl_workbook_from_xl(fullname, app_target=None, hwnd=None): """ Use GetActiveObject whenever possible, GetObject with a file path will only work if the file has been registered in the RunningObjectTable (ROT). Sometimes, e.g. if the files opens from an untrusted location, it doesn't appear in the ROT. app_target is only used on Mac. """ num_of_instances = get_number_of_instances() if num_of_instances < 2: xl_app = GetActiveObject('Excel.Application') xl_workbook = xl_app.ActiveWorkbook else: if not is_file_open(fullname): # This means that the file doesn't appear in the ROT. If it's in the first instance of # Excel, we can still get it with GetActiveObject xl_app = GetActiveObject('Excel.Application') xl_workbook = xl_app.ActiveWorkbook else: xl_workbook = GetObject(fullname) xl_app = xl_workbook.Application if str(xl_app.hwnd) != hwnd: # The check of the window handle also works when the same file is opened # in two instances, whereas the comparison of fullpath would fail raise Exception( "Can't establish connection! " "Try to open the file in the first instance of Excel or " "change your trusted location/document settings or " "set OPTIMIZED_CONNECTION = True.") return xl_workbook
def Setup(self, plugin, eventHandler): self.plugin = plugin self.eventHandler = eventHandler try: self.comInstance = GetActiveObject("MediaJukebox Application") WithEvents(self.comInstance, self.eventHandler) self.eventHandler.comInstance = self.comInstance except: pass
def getCurrentSelection(): selection = GetActiveObject( 'Outlook.Application').ActiveExplorer().Selection filenames = [] for n in xrange(1, selection.Count + 1): filename = persistence.get_temp_file(suffix='.eml') saveItem(selection.Item(n), filename) filenames.append(filename) return filenames
class AIFileHandler: def __init__(self, files_path, base_path): self.app = GetActiveObject("Illustrator.Application") self.files_path = files_path self.base_path = base_path def process_file(self, file_name): print(f'Processing file {file_name}') doc = self.app.Open(f'{self.files_path}/{file_name}') layers = doc.Layers print(f'Total layers: {len(layers)}') png_export_options = win32.Dispatch("Illustrator.ExportOptionsPNG24") png_export_options.horizontalScale = 200 png_export_options.verticalScale = 200 image_capture_options = win32.Dispatch("Illustrator.imageCaptureOptions") image_capture_options.resolution = 250 image_capture_options.transparency = True image_capture_options.antiAliasing = True svg_export_options = win32.Dispatch("Illustrator.ExportOptionsSVG") svg_export_options.fontType = 2 svg_export_options.embedRasterImages = True # svg_export_options.cssProperties = 3 svg_export_options.fontSubsetting = 1 # aiNoFonts for layer in layers: layer.visible = False for layer in layers: print(f'Processing layer {layer.name}...') layer.visible = True if len(layer.TextFrames) != 1 or len(layer.GroupItems) != 1: print(f'❗ Fail to export layer {layer.name}') layer.visible = False continue text_frame = layer.TextFrames[0] exported_name = text_frame.contents text_frame.selected = True self.app.ExecuteMenuCommand("hide") text_frame.selected = False group = layer.GroupItems[0] bounds = group.controlBounds group.selected = True # doc.Export(ExportFile=f'{exported_name}.png',ExportFormat=5,Options=png_export_options) doc.ImageCapture(f'{self.base_path}/{exported_name}.png', group.controlBounds, image_capture_options) doc.FitArtboardToSelectedArt(0) doc.Export(ExportFile=f'{self.base_path}/{exported_name}.svg',ExportFormat=3, Options=svg_export_options) group.selected = False layer.visible = False print(f'✓ Succeed to export layer {layer.name}') # break print(f'Exported file {file_name}\r\n')
def get_inventor(self): try: oApp = GetActiveObject('Inventor.Application') except Exception as e: print(e) oApp = Dispatch('Inventor.Application') oApp.Visible = True self._mod = gencache.EnsureModule( '{D98A091D-3A0F-4C3E-B36E-61F62068D488}', 0, 1, 0) self._application = self._mod.Application(oApp)
def send_to_ps(filename): try: app = GetActiveObject("Photoshop.Application") except Exception as e: print( "couldn't find an opened photoshop. Will try to open a new session." ) app = Dispatch("Photoshop.Application") doc = app.Open(filename)
def getCurrentSelection(): obj = GetActiveObject('Outlook.Application') exp = obj.ActiveExplorer() sel = exp.Selection ret = [] for n in xrange(1, sel.Count + 1): src = tempfile.NamedTemporaryFile( suffix='.eml') # Will be deleted automagically src.close() sel.Item(n).SaveAs(src.name, 0) src = file(src.name, 'rb') # Okay. In the case of HTML mails, Outlook doesn't put # a blank line between the last header line and the # body. This assumes that the last header is # Subject:. Hope it's true. # States: # 0 still in headers # 1 subject: header seen, blank line not written # 2 all headers seen, blank line written # 2 in body name = persistence.get_temp_file(suffix='.eml') dst = file(name, 'wb') try: s = 0 for line in src: if s == 0: dst.write(line) if line.lower().startswith('subject:'): dst.write('X-Outlook-ID: %s\r\n' % str(sel.Item(n).EntryID)) s = 1 elif s == 1: dst.write('\r\n') if line.strip() != '': dst.write(line) s = 2 else: dst.write(line) finally: dst.close() if os.name == 'nt': os.chmod(name, stat.S_IREAD) ret.append(name) return ret
def openMailWithOutlook(filename): id_ = None for line in file(filename, 'r'): if line.startswith('X-Outlook-ID:'): id_ = line[13:].strip() break elif line.strip() == '': break if id_ is None: return False from win32com.client import GetActiveObject # pylint: disable=F0401 app = GetActiveObject('Outlook.Application') app.ActiveExplorer().Session.GetItemFromID(id_).Display() return True
def __init__(self): if sys.platform != 'linux2': self.xl_window = GetActiveObject("Excel.Application") self.xlApp = Dispatch(self.xl_window).Application self.current_workbook_object = None self._update_workbooks_() self.current_sheet_object = None self._update_sheets_()
def __init__(self, package_name): self._sim = None # SimulationX application self._package_name = package_name self._items = [] self._type_annotations = ('Documentation.info', 'Documentation.revisions', 'obsolete', 'missingInnerMessage', 'unassignedMessage') self._annotations = ('Dialog.tab', 'Dialog.group', 'Dialog.loadSelector.filter', 'Dialog.loadSelector.caption', 'Dialog.saveSelector.filter', 'Dialog.saveSelector.caption') try: # Open SimulationX try: self._sim = GetActiveObject(simulationx_appid) except: self._sim = Dispatch(simulationx_appid) # Show SimulationX window self._sim.Visible = True # Wait till SimulationX is initialized if self._sim.InitState == simUninitialized: while self._sim.InitState != simInitBase: sleep(0.1) # SimulationX in non-interactive mode self._sim.Interactive = False # Load libraries if self._sim.InitState == simInitBase: self._sim.InitSimEnvironment() pkg = self._sim.Lookup(package_name) if pkg is not None: self._fill_data(pkg, package_name) else: logging.error('Package ' + package_name + ' not found.') except pywintypes.com_error as error: logging.error('SimulationX: COM error.') except: print('SimulationX: Unhandled exception.') import traceback logging.error(traceback.format_exc()) finally: try: if self._sim is not None: self._sim.Interactive = True except: pass
def get_illustrator(verbose=False): """ Targets an open instance of Illustrator, or opens Illustrator. :param verbose: bool, optional if True, prints out details of task :return: COM obj, required reference to Illustrator (type win32com.client.CDispatch) """ print('Targeting or opening Illustrator...') if verbose else None try: app = GetActiveObject('Illustrator.Application') except pywintypes.com_error: app = Dispatch('Illustrator.Application') return app
def start(): # Defining necessary variables app = GetActiveObject("Photoshop.Application") psApp = win32com.client.Dispatch("Photoshop.Application") doc = psApp.Application.ActiveDocument docRef = app.ActiveDocument # Logs the current layer previousLayer = docRef.activeLayer.name # Logs the current tool with Session() as ps: tool = ps.app.currentTool # Goes to the top most layer docRef.ActiveLayer = docRef.Layers.Item(1) # Plays the action "Magic Wand for Selection Script" in group "Selection Script Group" in the Actions panel # Sets the tool to Magic Wand app.DoAction('Magic Wand for Selection Script', 'Selection Script Group') # Waits for the left click # If it a mouse click that is not the left mouse button, does nothing def on_click(x, y, button, pressed): while button == mouse.Button.left: return False with Listener(on_click=on_click) as listener: listener.join() # After left click, sets the tool as the the tool that was selected previously ps.app.currentTool = tool # Goes to the layer that was previously active docRef.ActiveLayer = doc.ArtLayers[previousLayer]
def get_xl_workbook_from_xl(fullname): """ Under certain circumstances, only the GetActiveObject call will work (e.g. when Excel opens with a Security Warning, the Workbook will not be registered in the RunningObjectTable and thus not accessible via GetObject) """ if not is_file_open(fullname): xl_app = GetActiveObject('Excel.Application') xl_workbook = xl_app.ActiveWorkbook if xl_workbook.FullName.lower() != fullname.lower(): raise Exception( "Can't establish connection! " "Make sure that the calling workbook is the active one " "and is opened in the first instance of Excel.") else: xl_workbook = GetObject(fullname) return xl_workbook
def _get_opened_files_adobe_cc(obj: str) -> Iterator[Item]: """ Retrieve documents path of opened files of the given *obj* (application). Where application is one of the Adobe Creative Suite: >>> get_opened_files_via_com("Illustrator.Application") >>> get_opened_files_via_com("Photoshop.Application") Complete specs of supported applications: - Illustrator: https://www.adobe.com/devnet/illustrator/scripting.html - Photoshop: https://www.adobe.com/devnet/photoshop/scripting.html """ with suppress(Exception): app = GetActiveObject(obj) for doc in app.Application.Documents: path = doc.fullName pid = compute_fake_pid_from_path(path) yield pid, Path(path)
def get_xl_workbook_from_xl(fullname): """ Under certain circumstances, only the GetActiveObject call will work (e.g. when Excel opens with a Security Warning, the Workbook will not be registered in the RunningObjectTable and thus not accessible via GetObject) """ if not PY3: # On Windows, Python uses the name 'mbcs' to refer to whatever the currently configured file system encoding is # TODO: check if this is needed or just a duplicate of the equivalent code in is_file_open if isinstance(fullname, str): fullname = unicode(fullname.lower(), 'mbcs') if not is_file_open(fullname): # Windows doesn't allow to simultaneously work with two versions of Excel, so we don't need to use app_target xl_app = GetActiveObject('Excel.Application') xl_workbook = xl_app.ActiveWorkbook if xl_workbook.FullName.lower() != fullname.lower(): raise Exception( "Can't establish connection! " "Make sure that the calling workbook is the active one " "and is opened in the first instance of Excel.") else: xl_workbook = GetObject(fullname) return xl_workbook
def main(): uiApplication = GetActiveObject('STK12.Application') uiApplication.Visible = True root = uiApplication.Personality2 graph = Graph("bolt://localhost:7687", auth=("neo4j", "ssr")) ASO_type = int(input("Enter 1 or 2 to score either: (1) an ASO already in orbit or (2) a new ASO - ")) if ASO_type == 1: norad_id = input("Input the NORAD ID for the ASO you want to score: ") aso_orb = query_orbit(norad_id, graph) elif ASO_type == 2: aso_orb = {} SMA = float(input("Enter the planned semimajor axis in kilometers: ")) aso_orb['SMA'] = SMA * 1000 inclination = float(input("Enter the planned inclination of the orbit in degrees: ")) aso_orb['Inc'] = math.radians(inclination) eccentricity = float(input("Enter the planned eccentricity of the orbit: ")) aso_orb['Ecc'] = eccentricity raan = float(input("Enter the planned right ascension of the ascending node in degrees: ")) aso_orb['RAAN'] = math.radians(raan) argp = float(input("Enter the planned argument of perigee in degrees: ")) aso_orb['ArgP'] = math.radians(argp) scenario = root.CurrentScenario # build satellite satellite = scenario.Children.New(18, "ASO") keplerian = satellite.Propagator.InitialState.Representation.ConvertTo(1) keplerian.LocationType = 5 keplerian.SizeShape.Eccentricity = aso_orb['Ecc'] keplerian.SizeShape.SemiMajorAxis = aso_orb['SMA'] / 1000 keplerian.Orientation.Inclination = math.degrees(aso_orb['Inc']) keplerian.Orientation.ArgOfPerigee = math.degrees(aso_orb['ArgP']) # deg keplerian.Orientation.AscNode.Value = math.degrees(aso_orb['RAAN']) # deg keplerian.Location.Value = 0 # Apply the changes made to the satellite's state and propagate: satellite.Propagator.InitialState.Representation.Assign(keplerian) satellite.Propagator.Propagate() # detectability scoring radar_detect_results = pd.DataFrame(columns=['Metric', 'Value', 'Tier', 'Score']) prob_detection = radar_detectability(root) radar_detect_results = fill_d_dataframe(radar_detect_results, prob_detection) print(radar_detect_results) # optical_detectability(root) # trackability scoring radar_results = pd.DataFrame(columns=['Metric', 'Value', 'Tier', 'Score']) optical_results = pd.DataFrame(columns=['Metric', 'Value', 'Tier', 'Score']) avg_pass, avg_coverage, avg_interval = radar_trackability(aso_orb, root) opt_pass, opt_coverage, opt_int = optical_trackability(aso_orb, root) radar_results = fill_dataframe(radar_results, avg_pass, avg_coverage, avg_interval) optical_results = fill_dataframe(optical_results, opt_pass, opt_coverage, opt_int) print(radar_results) radar_score = radar_results['Score'].mean() print("\nOverall T Radar Score: {}\n".format(radar_score)) print(optical_results) optical_score = optical_results['Score'].mean() print("\nOverall T Optical Score: {}".format(optical_score))
def __init__(self, files_path, base_path): self.app = GetActiveObject("Illustrator.Application") self.files_path = files_path self.base_path = base_path
# This script demonstrates how to use the action manager to execute a # previously defined action liek the default actions that ships with Photoshop # Or one that you've created yourself. The name of the action comes from # Photoshop's Actions Palette from win32com.client import Dispatch, GetActiveObject, GetObject # Start up Photoshop application # Or get Reference to already running Photoshop application instance # app = Dispatch('Photoshop.Application') app = GetActiveObject("Photoshop.Application") fileName = "C:\Git\photoshop-scripting-python\PS_Samples_Files\Layer Comps.psd" docRef = app.Open(fileName) app.DoAction('Molten Lead', 'Default Actions')
# Create a stroke around the current selection. # Set the stroke color and width of the new stroke. from win32com.client import Dispatch, GetActiveObject from comtypes.client import GetActiveObject, CreateObject # Start up Photoshop application # Or get Reference to already running Photoshop application instance # app = Dispatch('Photoshop.Application') app = GetActiveObject("Photoshop.Application") if len([(i, x) for i, x in enumerate(app.Documents, 1)]) > 0: if app.ActiveDocument.ActiveLayer.IsBackgroundLayer == False: psPixels = 1 strtRulerUnits = app.Preferences.RulerUnits app.Preferences.RulerUnits = psPixels selRef = app.ActiveDocument.Selection offset = 10 selBounds = ((offset, offset), (app.ActiveDocument.Width - offset, offset), (app.ActiveDocument.Width - offset, app.ActiveDocument.Height - offset), (offset, app.ActiveDocument.Height - offset)) selRef.Select(selBounds) selRef.SelectBorder(5) # create text color properties strokeColor = CreateObject("Photoshop.SolidColor") strokeColor.CMYK.Cyan = 20 strokeColor.CMYK.Magenta = 90
# Classic Hello World example from win32com.client import Dispatch, GetActiveObject, GetObject # Start up an Illustrator application # app = Dispatch('Photoshop.Application') # Or get Reference to already running Illustrator application instance app = GetActiveObject("Illustrator.Application") docRef = app.Documents.Add() rectRef = docRef.PathItems.Rectangle(700, 50, 100, 100) areaTextRef = docRef.TextFrames.AreaText(rectRef) areaTextRef.Contents = "Hello World!"
class JRMCThreadWorker(eg.ThreadWorker): comInstance = None plugin = None eventHandler = None def Setup(self, plugin, eventHandler): self.plugin = plugin self.eventHandler = eventHandler try: self.comInstance = GetActiveObject("MediaJukebox Application") WithEvents(self.comInstance, self.eventHandler) self.eventHandler.comInstance = self.comInstance except: pass def Finish(self): if self.comInstance: del self.comInstance def SetActiveZone(self, whichZone): zonesInstance = self.comInstance.GetZones() nZones = zonesInstance.GetNumberZones() if whichZone > nZones or whichZone < 0: eg.PrintError("Invalid zone requested", whichZone) return zonesInstance.SetActiveZone(whichZone) Payload = {} Payload["zone"] = zonesInstance.GetZoneName(whichZone) self.plugin.TriggerEvent("ZoneChanged", Payload) def SyncZones(self, srcZone, dstZone): zonesInstance = self.comInstance.GetZones() nZones = zonesInstance.GetNumberZones() if srcZone > nZones or srcZone < 0: eg.PrintError("Invalid zone requested", srcZone) return if dstZone > nZones or dstZone < 0: eg.PrintError("Invalid zone requested", dstZone) return zonesInstance.SynchronizeZones(srcZone, dstZone) Payload = {} Payload["source zone"] = zonesInstance.GetZoneName(srcZone) Payload["destination zone"] = zonesInstance.GetZoneName(dstZone) self.plugin.TriggerEvent("ZonesSynchronized", Payload) def SetPlaylist(self, plistName): playlistsInstance = self.comInstance.GetPlaylists() nPlaylists = playlistsInstance.GetNumberPlaylists() for i in range(nPlaylists): plist = playlistsInstance.GetPlaylist(i) if plistName == plist.Name: break else: plist = None #Don't want to pass in ID, rather find playlist by name to make config easier #plist = self.comInstance.GetPlaylistByID(plistID) if plist == None: eg.PrintError("Invalid playlist requested: ", "Name =", plistName) return files = plist.GetFiles() n = files.GetNumberFiles() if n < 1: eg.PrintNotice("Requested Playlist has no songs.", "Name =", plistName, "ID =", plistID) return current = self.comInstance.GetCurPlaylist() current.RemoveAllFiles() i = 0 while i < n: file = files.GetFile(i) current.AddFile(file.Filename, i) #print "Adding",file.Filename,str(i) i = i + 1 if (current.Shuffle): current.ReShuffleFiles() current.Position = 0 playback = self.comInstance.GetPlayback().Play()
import time from win32com.client import Dispatch, GetActiveObject, GetObject # This is a test script written to see how Python scripting works in executing # Photoshop actions, ExecuteAction() # Where did I get all this action stuffs(ActionDescriptor, ActionReference, CharIDToTypeID etc)? # It's generated by a plugin Photoshop provides or you can generate one yourself # See https://www.adobe.com/devnet/photoshop/scripting.html # Start up Photoshop application # app = Dispatch('Photoshop.Application') # Or get Reference to already running Photoshop application # app = GetObject(Class="Photoshop.Application") app = GetActiveObject("Photoshop.Application") # psDisplayNoDialogs is a PS COM constant, see pscc2018.py or scripting COM psDisplayNoDialogs = 3 for index, x in enumerate(range(50)): # app.DoAction('Sepia Toning (layer)', 'Default Actions') # Execute an existing action from action palette idPly = app.CharIDToTypeID("Ply ") desc8 = Dispatch('Photoshop.ActionDescriptor') idnull = app.CharIDToTypeID("null") ref3 = Dispatch('Photoshop.ActionReference') idActn = app.CharIDToTypeID("Actn") ref3.PutName(idActn, "Sepia Toning (layer)") idASet = app.CharIDToTypeID("ASet") ref3.PutName(idASet, "Default Actions") desc8.PutReference(idnull, ref3)
import math from win32com.client import Dispatch, GetActiveObject, gencache, constants try: invApp = GetActiveObject('Inventor.Application') except: invApp = Dispatch('Inventor.Application') invApp.Visible = True mod = gencache.EnsureModule('{D98A091D-3A0F-4C3E-B36E-61F62068D488}', 0, 1, 0) invApp = mod.Application(invApp) # invApp.SilentOperation = True # Create a new part invDoc = invApp.Documents.Add(constants.kPartDocumentObject, "", True) # Casting Document to PartDocument invPartDoc = mod.PartDocument(invDoc) compdef = invPartDoc.ComponentDefinition # Create a sketch xyPlane = compdef.WorkPlanes.Item(3) origin_point = invApp.TransientGeometry.CreatePoint(0, 0, 0) x_axis = invApp.TransientGeometry.CreateUnitVector(1, 0, 0) y_axis = invApp.TransientGeometry.CreateUnitVector(0, 1, 0) l = 4 h = 2*(3**0.5) r = 4/(3**0.5) for i in range(0, 30): angle = i*0.1
# This script demonstrates how to create a new layer and set its kind. from win32com.client import Dispatch, GetActiveObject, GetObject # Start up Photoshop application # Or get Reference to already running Photoshop application instance # app = Dispatch('Photoshop.Application') app = GetActiveObject("Photoshop.Application") # PS constants, see psCC2018.py psPixels = 1 psNewRGB = 2 psWhite = 1 psTextLayer = 2 # from enum PsLayerKind strtRulerUnits = app.Preferences.RulerUnits if len(app.Documents) < 1: if strtRulerUnits is not psPixels: app.Preferences.RulerUnits = psPixels docRef = app.Documents.Add(320, 240, 72, None, psNewRGB, psWhite) else: docRef = app.ActiveDocument layerRef = docRef.ArtLayers.Add() layerRef.Kind = psTextLayer # Set the ruler back to where it was app.Preferences.RulerUnits = strtRulerUnits
#%% #from comtypes.client import GetActiveObject, CreateObject import pandas_datareader as pdr from matplotlib import pyplot as plt from scipy import interpolate import numpy as np from win32com.client import GetActiveObject, Dispatch #%% n = 0 #%% try: acad = GetActiveObject('AutoCAD.Application.23') #acad = CreateObject('AutoCAD.Application.23') doc = acad.ActiveDocument model = doc.ModelSpace except Exception as error: print(error) #%% try: n += 1 c3d1 = acad.GetInterfaceObject("AeccXUiLand.AeccApplication.9.0") n += 1 c3d2 = acad.GetInterfaceObject("AeccXUiRoadway.AeccRoadwayApplication.9.0") n += 1 #c3d1 = CreateObject("AeccXUiLand.AeccApplication.9.0") #c3d2 = CreateObject("AeccXUiRoadway.AeccRoadwayApplication.9.0") pass except Exception as error: print(error) print('\n' + str(n))
# This script demonstrates how you can use the action manager # to execute the Smart Sharpen filter. from win32com.client import Dispatch, GetActiveObject, GetObject # Start up Photoshop application # Or get Reference to already running Photoshop application instance # app = Dispatch('Photoshop.Application') app = GetActiveObject("Photoshop.Application") fileName = "C:\Git\PS_Samples_Files\Layer Comps.psd" docRef = app.Open(fileName) nLayerSets = docRef.LayerSets nArtLayers = docRef.LayerSets.Item(len(nLayerSets)).ArtLayers docRef.ActiveLayer = docRef.LayerSets.Item(len(nLayerSets)).ArtLayers.Item(len(nArtLayers)) def SmartSharpen(inAmount, inRadius, inNoise): idsmartSharpenID = app.stringIDToTypeID("smartSharpen") desc37 = Dispatch('Photoshop.ActionDescriptor') idpresetKind = app.stringIDToTypeID("presetKind") idpresetKindType = app.stringIDToTypeID("presetKindType") idpresetKindCustom = app.stringIDToTypeID("presetKindCustom") desc37.putEnumerated(idpresetKind, idpresetKindType, idpresetKindCustom) idAmnt = app.charIDToTypeID("Amnt") idPrc = app.charIDToTypeID("#Prc")
# Crop and rotate the active document. from win32com.client import Dispatch, GetActiveObject, GetObject # Start up Photoshop application # Or get Reference to already running Photoshop application instance # app = Dispatch('Photoshop.Application') app = GetActiveObject("Photoshop.Application") # PS constants, see psCC2018.py psPixels = 1 psNewRGB = 2 psWhite = 1 fileName = "C:\Git\photoshop-scripting-python\PS_Samples_Files\Layer Comps.psd" srcDoc = app.Open(fileName) strtRulerUnits = app.Preferences.RulerUnits if strtRulerUnits is not psPixels: app.Preferences.RulerUnits = psPixels # crop a 10 pixel border from the image bounds = [10, 10, srcDoc.Width - 10, srcDoc.Height - 10] srcDoc.RotateCanvas(45) srcDoc.Crop(bounds) # set ruler back to where it was app.Preferences.RulerUnits = strtRulerUnits
from win32com.client import GetActiveObject, Dispatch, CastTo, GetObject # (vla-getinterfaceobject (vlax-get-acad-object) "AeccXUiLand.AeccApplication.13.2") try: acad = GetActiveObject('AutoCAD.Application.23') pass except Exception as error: print(error) quit() doc = acad.ActiveDocument model = doc.ModelSpace doc.Utility.Prompt('\nSelecione uma Polylinha : ') poly = doc.Utility.GetEntity() limit = list(poly[0].GetBoundingBox()) x1, y1 = limit[0][0], limit[0][1] x2, y2 = limit[1][0], limit[1][1] for p in [x1, y1, x2, y2]: print(p) pass n = 0 while n != -1: try: c = poly[0].Coordinate(n) print(c) n += 1 pass
def _connect_to_running_excel(visible=True): xl = GetActiveObject('Excel.Application') xl.Visible = visible return xl