def main():
    acad = Autocad()
    print u'Примерный подсчет занимаемого места'
    print '%-20s| %s' % (u'Имя щита', u'Общее число модулей')
    for layout in acad.iter_layouts():
        table = acad.find_one('table', layout.Block, lambda x: x.Columns == 5)
        if not table:
            continue

        total_modules = 0
        row = -1
        while row < table.Rows:
            row += 1
            item_str = mtext_to_string(table.GetText(row, 2))
            item_str = item_str.replace(u'четырехполюсный', u'4-х')\
                               .replace(u'трехполюсный', u'3-х')\
                               .replace(u'двухполюсный', u'2-х')\
                               .replace(u'однополюсный', u'1-но')
            m = re.match(ur'.*(\d)-([xх]|но).*', item_str)
            if m:
                n_modules = int(m.group(1))
                quantity = int(mtext_to_string(table.GetText(row, 3)))
                row += 1  # skip next row
            else:
                m = re.match(ur'(\d)[PР].*', item_str)
                if not m:
                    continue
                n_modules = int(m.group(1))
                quantity = int(mtext_to_string(table.GetText(row - 1, 3)))
            total_modules += n_modules * quantity
        print '%-20s| %s' % (layout.Name, total_modules)
Example #2
2
def draw_map(nodes, edges):
    acad = Autocad()
    acad.prompt("Hello, Autocad from Python\n")
    print acad.doc.Name

    for edge in edges.itervalues():
        p1 = APoint(nodes[edge.start_node_id].x, nodes[edge.start_node_id].y)
        p2 = APoint(nodes[edge.end_node_id].x, nodes[edge.end_node_id].y)
        line = acad.model.AddLine(p1, p2)
        line.Color = edge.edge_class
Example #3
0
    def draw_a_cloaking_mesh(self, timestamp, user_obj_id):
        acad = Autocad()
        acad.prompt("Autocad from Python - Draw A Cloaking Mesh\n")
        print acad.doc.Name

        #1. draw user locations
        query_list = self.query_log.frames[timestamp]  # timestamp
        point_dict = {}  #[obj_id] -> location
        for query in query_list:
            point_dict[query.obj_id] = (query.x, query.y)

        acad.prompt("Autocad from Python - Draw Users in Node Layer\n")
        for obj_id in self.positive_mc_set[self.user_mc_set[user_obj_id]]:
            p1 = APoint(point_dict[obj_id][0], point_dict[obj_id][1])
            p = acad.model.AddPoint(p1)
            p.Layer = "Node"
            p.Color = Color.RED

        #2. draw mesh's segments
        acad.prompt("Autocad from Python - Draw Users in Node Layer\n")
        for seg in self.user_mesh[user_obj_id]:
            p1 = APoint(seg.start_x, seg.start_y)
            p2 = APoint(seg.end_x, seg.end_y)
            line = acad.model.AddLine(p1, p2)
            line.Layer = "Mesh"
            line.Color = Color.GREEN

        print "DONE"
    def execute(self, data):
        #self.data = copy.deepcopy(data)
        self.data = data
        self.scale = self._getScale()#scale содержит гостовский масштаб
        self.scaledCellSize = self.scale * self.data["CellSize"]

        self.cells = Cells(self.scaledCellSize, self.data["Radius"] * self.scale) # содержит блоки-конструктор для отрисовки конвейера
        self.acad = Autocad(create_if_not_exists=True)  # so far app is not openw
        self.acad.app.Documents.Open(os.getcwd() + "/Files/AutoCAD_templates/А1.dwg")
        self.acad.ActiveDocument.SaveAs(tempfile.gettempdir() + "/name.dwg") #TODO вписать имя из словаря data
        self.layers = self._defineLayers()
        self.pathQmax = "D:\YandexDisk\#SKOLTECH\Early Research Tecnomax\pythonScript\Files\AutoCAD_cabines\Q-MAX.dwg"
        # TODO create windows attention about that in that time autocad will be opening
        #self.acad.Application.Documents.open(self.pathQmax)
        """l = []
        for obj in self.acad.iter_objects():
            try:
                if obj.layer == "Границы Цеха":
                    l.extend(list(obj.coordinates)) #use extend because will be 1 list

            except Exception:
                print(f"Exception: ошибка при итерации по файлу {self.path2dwg}")
                continue
        """

        #self.acad.Application.Documents.Add()
        self._conveyorsDraw()
        self._scaleFigures()
        self._figuresDraw()

        #x = input() #ошибка возникает дальше при вызове канваса
        return "done"
Example #5
0
def main():
    acad = Autocad()
    layout = acad.doc.ActiveLayout
    table = acad.find_one('table', layout.Block)
    if not table:
        return
    print_table_info(table, 3)
Example #6
0
 def __init__(self, insert_point=None, num=0, name=0):
     self.name = "frame" + str(name)
     self.num = num
     self.X = insert_point[0]
     self.Y = insert_point[1]
     self.insertionPnt = APoint(self.X, self.Y)
     self.acad = Autocad(create_if_not_exists=True)
     self.draw()
Example #7
0
 def close_other(self):
     self.get_doc()
     lst = []
     docs = Autocad(create_if_not_exists=True).app.documents
     for i in range(docs.count):
         if docs[i].Name != self.name:
             lst.append(docs[i].Name)
     for doc in lst:
         docs[doc].close()
Example #8
0
 def __init__(self, text=None, insert_point=None):
     self.text = text
     self.X = insert_point[0]
     self.Y = insert_point[1]
     self.insertionPnt = APoint(self.X, self.Y)
     self.input_point = APoint(self.X + 250, self.Y + 400)
     self.output_point = APoint(self.X + 250, self.Y)
     self.acad = Autocad(create_if_not_exists=True)
     self.draw()
Example #9
0
def draw_points_in_layer():
    acad = Autocad()
    acad.prompt("Autocad from Python - Draw Points in Layer\n")
    print acad.doc.Name

    for i in range(8):
        p1 = APoint(i * 1000, 1000)
        p = acad.model.AddPoint(p1)
        p.Layer = "Node"
        p.Color = i
Example #10
0
 def __init__(self):
     self.acad = Autocad(
         create_if_not_exists=True)  # so far app is not open
     self.dimscale = 100  # annotative scale for sizes #TODO масштаб должен настраиваться автоматически
     print("AutoCad запущен. Создан документ", self.acad.doc.Name)
     self.acad.Application.Documents.open(
         "d:\Picture_ENG.dwg")  #TODO путь с пробелами вызывает трудности
     print(self.acad.doc.Name)
     self.acad.size_scale(
         self.dimscale)  # setting annotative scale for sizes
     self._clear()  #стирание из файла
Example #11
0
def main():
    acad = Autocad()
    objects = None
    if 'i' in sys.argv[1:]:
        objects = acad.get_selection('Select objects')
    lamps = defaultdict(int)
    for lamp in iter_lamps(acad, objects):
        lamps[lamp.mark] += int(lamp.number)
    print '-' * 79
    for mark, number in sorted(lamps.iteritems()):
        print '%-20s | %s' % (mark, number)
Example #12
0
def main():
    filename = sys.argv[1] if sys.argv[1:] else 'names.txt'
    output = codecs.open(filename, "w", encoding='utf-8')
    acad = Autocad()
    for doc in acad.app.Documents:
        print doc.Name
        output.write(u'%s\n' % ('-' * 50))
        output.write(u"    %s\n" % doc.Name)
        output.write(u'%s\n' % ('-' * 50))
        for drawing_name in iter_drawings_names(acad, doc):
            output.write(u'%s\n' % drawing_name)
Example #13
0
def main():
    '''gui portion'''
    cad = Autocad(create_if_not_exists=True)
    root = Tk()
    root.geometry('300x100+1000+500')
    button_compare = Button(root, text='Compare', command=lambda: compare(cad))
    button_loadatt = Button(root,
                            text='Load_att',
                            command=lambda: load_att(cad))
    button_compare.pack(pady=10, padx=10)
    button_loadatt.pack(pady=10, padx=10)
    root.mainloop()
Example #14
0
def draw():
    acad = Autocad(create_if_not_exists=False)
    property.get_values()
    if is_closed() == False:
        return tk.messagebox.showerror('Error', 'Geometry is not closed')
    else:
        try:
            polyline = acad.model.AddPolyline(array.array('d', property.array))
            acad.prompt('Drawing successful!')
        except:
            return tk.messagebox.showerror('Error',
                                           'No AutoCAD instance detected')
Example #15
0
    def Auto_Mark(self):
        # 连接CAD
        acad = Autocad(create_if_not_exists=True)

        # 设定变量
        for leader in acad.iter_objects('Leader'):
            leader.DimensionLineColor = 2

        for dim in acad.iter_objects('Dimension'):
            attribute = dir(dim)
            dim.TextColor = 2
            dim.DimensionLineColor = 2
            dim.ExtensionLineColor = 2
Example #16
0
def run():
    acad = Autocad(create_if_not_exists=True)
    doc = acad.doc
    print(doc.Name)
    xref_purge(doc)
    if bind_xref_1(doc):
        print("bind_xref_1 successful")
    elif bind_xref_2(doc):
        print("bind_xref_2 successful")
    elif bind_xref_3(doc):
        print("bind_xref_3 successful")
    else:
        print("bind xref all failed")
Example #17
0
def tin():
    """
    从文件中读取点,生成tin
    """
    acad = Autocad()
    ptlist = []
    num = acad.doc.Utility.GetInteger('请选择从:\n1.从文件中读取点 2.现有点(当前图层)生成三角网')
    if num == 1:
        fname = tkFileDialog.askopenfilename(title=u"选择文件",
                                             filetypes=[("text file", "*.txt"),
                                                        ("all", "*.*")],
                                             initialdir=r"D:\学习\计算机图形学")
        f = open(fname)
        lines = f.readlines()
        f.close()
        poLayer = acad.doc.Layers.Add('point')
        acad.doc.ActiveLayer = poLayer
        for i in range(1, len(lines), 2):
            t = lines[i].split(',')
            ap = APoint(float(t[1]), float(t[2]), float(t[3]))
            ptlist.append(ap)
            acad.model.AddPoint(ap)
    elif num == 2:
        try:
            acad.doc.SelectionSets.Item("SS1").Delete()
        except Exception:
            print('Delete selection failed')
        ss = acad.doc.SelectionSets.Add('SS1')
        ss.Select(ACAD.acSelectionSetAll, aShort([0, 8]), ['POINT', 'point'])
        for i in range(ss.Count):
            c = ss.Item(i).Coordinates
            ptlist.append(APoint(ss.Item(i).Coordinates))
    ptlist = PointSet(ptlist)
    minpo, maxpo = ptlist.GetBoundingBox()
    acad.app.ZoomWindow(minpo, maxpo)
    lineLayer = acad.doc.Layers.Add('line')
    lineLayer.Color = ACAD.acRed
    acad.doc.ActiveLayer = lineLayer
    points = np.array(ptlist)
    points = points[:, 0:2]
    tri = Delaunay(points)
    for simplex in tri.simplices:
        aplist = [
            APoint(ptlist[simplex[0]]),
            APoint(ptlist[simplex[1]]),
            APoint(ptlist[simplex[2]])
        ]
        lwp = acad.model.AddLightWeightPolyline(toLightWeightPolyline(aplist))
        lwp.Closed = True
    def execute(self, data):
        self.data = data
        self.acad = Autocad(
            create_if_not_exists=True)  # so far app is not open
        self.path2dwg = self.data[
            "Строительная подоснова"]  # refer to the key to the field where the link to this file
        if self.path2dwg == "":
            return "next"  #если не указан путь до файла, то перейти к следующему объекту
        # TODO create windows attention about that in that time autocad will be opened
        self.acad.Application.Documents.open(self.path2dwg)
        self._read()
        self.acad.Application.Documents.close(
        )  # close previous file in autocad

        return "next"
Example #19
0
def run():
    acad = Autocad(create_if_not_exists=True)
    acad.Application.LoadARX("D:\\CapolCAD\\lsp\\iWCapolPurgeIn.arx")
    doc = acad.doc
    print(doc.Name)
    doc = remove_unload_xref(doc)
    xref_purge(doc)
    if bind_xref_1(doc):
        print("bind_xref_1 successful")
    elif bind_xref_2(doc):
        print("bind_xref_2 successful")
    elif bind_xref_3(doc):
        print("bind_xref_3 successful")
    else:
        print("bind xref all failed")
def find_and_replace(file):
    #Read to excel file
    df = pd.read_excel(file, sheet_name=0)
    files = df['files'].tolist()
    find = df['find'].tolist()
    replace_with = df['replace'].tolist()

    dico = {}

    for index in range(len(files)):
        dico[str(files[index])] = [str(find[index]), str(replace_with[index])]
    #get files frm current dir and current dir path
    dwgfiles = filter(os.path.isfile, os.listdir( os.curdir ) )
    cwd = os.path.abspath(os.path.curdir) #current working dir

    
    for f in dwgfiles: #loop on files
        if f.endswith(".dwg"): #Choose Dwg files
            #Initiate AutoCad APP
            acad = win32com.client.Dispatch("AutoCAD.Application") 
            acad.Visible = True
            acad = Autocad() 

            #Open document
            acad.app.Documents.open(cwd + "/" + f)

            print(acad.doc.Name) #Curent file name

            doc = acad.ActiveDocument   # Document object 
            #Traverse the cad image object,Modifying Object Properties
            for entity in acad.ActiveDocument.ModelSpace:
                name = entity.EntityName
                if name == 'AcDbMText':
                    if dico[f][0] in entity.TextString:
                        #Modify object properties
                        text1 = str(entity.TextString)
                        text1 = text1.replace (dico[f][0], dico[f][1])
                        entity.TextString = text1
                elif name == 'AcDbText':
                    if dico[f][0] in entity.TextString:
                        #Modify object properties
                        text1 = str(entity.TextString)
                        text1 = text1.replace (dico[f][0], dico[f][1])
                        entity.TextString = text1
                
            doc.Close(True)
            acad = None
            print(f, ", Done")
Example #21
0
def stack(brick_length, brick_height, hor_bricks, ver_bricks):
    acad = Autocad(create_if_not_exists=True)
    acad.prompt('Hello, Autocad from Python\n')

    for ver_count in range(ver_bricks):
        for hor_count in range(hor_bricks):
            points = [
                hor_count*brick_length, ver_count*brick_height,
                hor_count*brick_length + brick_length, ver_count*brick_height,
                hor_count*brick_length + brick_length, ver_count*brick_height + brick_height,
                hor_count*brick_length, ver_count*brick_height + brick_height,
                ]
            points = array.array("d", points)
            pline = acad.model.AddLightWeightPolyline(points)
            pline.Closed = True
    
    return None
Example #22
0
def hatchCAD(dwg):
    acad = Autocad()
    doc = acad.Application.Documents.Open(dwg)
    patternName = "SOLID"
    PatternType = 0
    bAssociativity = True
    try:
        doc.ActiveLayer = doc.Layers("0")
        for obj in doc.Modelspace:
            if obj.Layer == "A1(行政办公用地)":
                obj.layer.Truecolor = 231
                hatchobj = obj.AddHatch(PatternType, patternName,
                                        bAssociativity)
                outerloop = obj.layer("A1(行政办公用地)")
                hatchobj.AppendOuterLoop(outerloop)
                hatchobj.Evaluate
            elif obj.Layer == "A2(文化设施用地)":
                obj.layer.Truecolor = 241
                hatchobj = obj.AddHatch(PatternType, patternName,
                                        bAssociativity)
                outerloop = obj.layer("A2(文化设施用地)")
                hatchobj.AppendOuterLoop(outerloop)
                hatchobj.Evaluate

            elif obj.Layer == "G2(防护绿地)":
                obj.layer.Truecolor = 94
                hatchobj = obj.AddHatch(PatternType, patternName,
                                        bAssociativity)
                outerloop = obj.layer("G2(防护绿地)")
                hatchobj.AppendOuterLoop(outerloop)
                hatchobj.Evaluate
            elif obj.Layer == "G3(广场用地)":
                obj.layer.Truecolor = 93
                hatchobj = obj.AddHatch(PatternType, patternName,
                                        bAssociativity)
                outerloop = obj.layer("G3(广场用地)")
                hatchobj.AppendOuterLoop(outerloop)
                hatchobj.Evaluate
            else:
                pass
    except:
        print u"%s填充不成功,请检查" % obj.name
    finally:
        doc.save()
        doc.close()
Example #23
0
    def __init__(self):
        self.lst=[]
        self.ls_ar=[] # 把@数据存入ls_ar中
        self.ls_inx=[] # 把@索引存入ls_inx中
        self.spx = 100  # area startx
        self.spy = 2000 #area starty
        self.rw = 300   #area width
        self.rh = 400   #area height
        self.lst_p4 = []  #point4 x,y value
        self.fh=3  # font height
        self.m=0   # how many guizi in lst
        self.acad = Autocad(create_if_not_exists=True)
        txtsytle=self.acad.ActiveDocument.TextStyles.Add('HIT_TxtStyle')
        self.acad.ActiveDocument.ActiveTextStyle=self.acad.ActiveDocument.TextStyles.Item('Standard')
        self.acad.ActiveDocument.ActiveTextStyle.SetFont('楷体',False,False,1,0 or 0)
        self.TestB_Lock()

        self.txtlst=[]
Example #24
0
def main():
    acad = Autocad()
    parser = optparse.OptionParser(usage=u'%prog [опции] [файл для результатов]')
    parser.add_option('-f', '--format',
                      choices=available_write_formats(), dest='format',
                      metavar='FORMAT', default='xls',
                      help=u"Формат файла (%s) по умолчанию - %%default" %
                           ', '.join(available_write_formats()))
    parser.add_option('-k', '--known', dest='known_targets',
                      metavar='FILE', default='', action='store',
                      help=u'Файл с заполненым полем "Конец" и очередностью '
                           u' записей. По умолчанию берется из существующего файла')
    parser.add_option('-q', '--quiet', action='callback',
                      callback=lambda *x: logging.disable(logging.WARNING),
                      help=u'"Тихий" режим (не печатать в консоль)')
    parser.add_option('-s', '--single', dest='single_doc', action='store_true',
                      default=False,
                      help=u'Собрать данные только из текущего документа '
                           u'(Собирает из всех по умолчанию)')
    parser.add_option('-c', '--no-known', dest='dont_use_known',
                      action='store_true', default=False,
                      help=u'Не использовать данные об очередности и поле "Конец"')
    options, args = parser.parse_args()

    output_file = args[0] if args else u"cables_from_%s.%s" % (acad.doc.Name, options.format)
    if not options.known_targets and not options.dont_use_known:
        options.known_targets = output_file
    known_targets = get_known_targets(options.known_targets)
    output_table = Table()
    if options.single_doc:
        documents = [acad.doc]
    else:
        documents = acad.app.Documents

    for doc in documents:
        try:
            cables = get_cables(acad, doc.Modelspace, known_targets)
            sorted_cables = sort_cables_by_targets(cables, known_targets)
            for row in sorted_cables:
                output_table.writerow([s for s in row])
        except Exception:
            logger.exception('Error while processing %s', doc.Name)
    output_table.save(output_file, options.format)
Example #25
0
def test1():
    #Test1: mesh testing

    acad = Autocad()
    acad.prompt("Hello, Autocad from Python\n")
    print acad.doc.Name

    p1 = APoint(0, 0)
    p2 = APoint(50, 25)
    for i in range(5):
        text = acad.model.AddText('Hi %s!' % i, p1, 2.5)
        acad.model.AddLine(p1, p2)
        acad.model.AddCircle(p1, 10)
        p1.y += 10

    dp = APoint(10, 0)
    for text in acad.iter_objects('Text'):
        print('text: %s at: %s' % (text.TextString, text.InsertionPoint))
        text.InsertionPoint = APoint(text.InsertionPoint) + dp

    for obj in acad.iter_objects(['Circle', 'Line']):
        print(obj.ObjectName)
Example #26
0
def get_balance():
    balance_type_dict = {
        1: ["returnable", "возвратные"],
        0: ["irrevocable", "невозвратные"]
    }
    poly_type = {
        1: {
            "type": "для ППТ-15",
        },
        2: {
            "type": "для Эфф. утеп.",
        }
    }
    result = {"returnable": {1: [], 2: []}, "irrevocable": {1: [], 2: []}}

    acad = Autocad(create_if_not_exists=True)
    doc = acad.doc
    is_continued = 1
    while is_continued == 1:
        balance_type = doc.Utility.GetInteger(
            "Выберите вид остатков и нажмите Enter\n(если возвратные - введите 1, если невозвратные - введите 2)\n"
        )
        received_type = doc.Utility.GetInteger(
            "Выберите вид утеплителя и нажмите Enter\n(если ППТ-15-А-Р - введите 1, если Эффективный утеплитель - введите 2)\n"
        )
        thikness = doc.Utility.GetInteger(
            "Введите толщину пакета утеплителя и нажмите Enter\n")
        chosen_type = poly_type[received_type]["type"]
        selected = get_selected(
            doc,
            f"Выберете возвратные остатки {chosen_type}, толщиной {thikness}")
        for index in range(selected.Count):
            item = selected.Item(index)
            result[balance_type_dict[balance_type][0]][received_type].append(
                (item.Area / 1000000) * (thikness / 1000))
        is_continued = doc.Utility.GetInteger(
            "Для того чтобы продолжить введите '1', для завершения введите '0'\n(для ввода доступны только вышеуказанные числа, иначе будет ошибка)\n"
        )
    return result
Example #27
0
def main():
    parser = optparse.OptionParser()
    parser.add_option('-f',
                      '--format',
                      choices=available_write_formats(),
                      dest='format',
                      metavar='FMT',
                      default='xls',
                      help=u"Формат файла (%s) по умолчанию - %%default" %
                      ', '.join(available_write_formats()))
    parser.add_option('-m',
                      '--model',
                      dest='include_model',
                      default=False,
                      action='store_true',
                      help=u"Включить пространство Модели в область поиска")

    options, args = parser.parse_args()
    acad = Autocad()
    filename = args[0] if args else u"exported_%s.%s" % (acad.doc.Name,
                                                         options.format)
    output_table = Table()
    extract_tables_from_dwg(acad, output_table, not options.include_model)
    output_table.save(filename, options.format)
Example #28
0
def bind_xref_3(doc):  #一级深度绑定
    doc_load(doc)
    xref_lst = get_lv1_xref(doc)
    if xref_lst:
        find_path = doc.Path
        for (name, path) in xref_lst:
            fpath = find_file(path, find_path)
            fpath = set_write(fpath)
            if fpath:
                doc2 = Autocad().app.documents.open(fpath)
                if bind_xref_1(doc2):
                    doc2.close(True)
                elif binf_xref_2(doc2):
                    doc2.close(True)
                else:
                    print("Can not bind xref: " + doc2.name)
                    doc2.close(False)
        if bind_xref_1(doc):
            return True
        elif bind_xref_2(doc):
            return True
        else:
            print("bind_xref_3 failed")
            return False
Example #29
0
from pyautocad import Autocad, APoint, distance
import json

acad = Autocad()

# db_circle = []
# n = 0
# for obj in acad.iter_objects('Circle'):
#     file = open('obj_cirlces.json', 'w')
#     db_circle.append({'Number': n, 'Centre': obj.Center, 'Layer': obj.Layer, 'ObjectName': obj.ObjectName})
#     n += 1
#     json.dump(db_circle, file, indent=1)
#     file.close()

db_lines = []
m = 0
for obj in acad.iter_objects('Line'):
    file = open('obj_lines.json', 'w')
    db_lines.append({
        'Number': m,
        'ObjectName': obj.ObjectName,
        'ObjectID': obj.ObjectID,
        'Handle': obj.Handle,
        'Length': obj.Length,
        'Layer': obj.Layer
    })
    m += 1
    json.dump(db_lines, file, indent=1)
    file.close()

pp = APoint(2210581.291, 488153.2095)
Example #30
-1
def test():
    acad = Autocad(create_if_not_exists=True)
    acad.prompt("Hello, Autocad from Python\n")
    acad.Application.LoadARX("D:\\CapolCAD\\lsp\\iWCapolPurgeIn.arx")
    print(acad.doc.Name)
    doc = acad.doc
    #print(get_count0(doc))
    #remove_count0(doc)
    remove_unload_xref(doc)