一个用python写的从数字高程格式文件(DEM)中提取水系的模块

SuperMap sqlserver数据库中点数据集到AutoCAD文本的转换

luobo posted @ 2012年11月15日 12:02 in 未分类 with tags supermap python autocad , 1538 阅读

转载请注明出处,谢谢合作

#!/usr/bin/env python
# -*- coding: cp936 -*-
'''
@brief 功能说明:
实现从supermap后台的mssql里点数据集到AutoCAD里文本型的转换。
要是改为多线程的效果可能会更好。但现在的处理量很小,用不着给自己找麻烦
@author 施峰<sf.cumt@163.com>
2011-10-4~2011-10-5
'''

import pyodbc
import logging
import comtypes.client
import numbers
import array
import re
import ConfigParser

def getconnect(db_type=None,db_arg=None):
    '''
    sql server:
        connector=pyodbc.connect('DRIVER={SQL SERVER};SERVER=LUOBO\\SQLEXPRESS;DATABASE=chengguuo')
    '''
    if db_type in ('MSSQL','JET'):
        try:
            connector = pyodbc.connect(db_arg)
        except :
            logging.error("数据库连接错误!")
            raise
        return connector

def getdrawscript(f=None):
    '''
    如果给定文件名则打开该CAD文件。
    如果没有给定文件名则认为待编辑的CAD文件已经打开。
    '''
    if not f:
        try:
            cad=comtypes.client.GetActiveObject('AutoCAD.Application') #这个可能有点问题
            cad.Visible=False
            drawingscript=cad.ActiveDocument
        except :
            logging.error("获得活动cad文件失败。请查看草稿文件是否已经打开,或请关闭除了草稿文件以外的所有cad文件。")
            raise
    else:
        try:
            cad=comtypes.client.CreateObject('AutoCAD.Application')
        except :
            logging.error("请确定本机上安装了autocad")
            raise
        try:
            drawingscript=cad.Documents.Open(f)
        except :
            logging.error("cad文件打开失败。")
            cad.Quit()
            raise
    return drawingscript

def getrows(sqlstring,connect=None,*args,**kargs):
    '''
    当返回大量记录时可以要占用大量内存空间
    >>> sqlstring = 'SELECT SmX,SmY,name FROM SMDTV_93'
    >>> connect = pyodbc.connect('DRIVER={SQL SERVER};SERVER=LUOBO\\SQLEXPRESS;DATABASE=chengguuo')
    >>> rows = getrows(sqlstring,connect)
    >>> isinstance(rows,list)
    True
    >>> row=rows[1]
    >>> isinstance(row[0],numbers.Real)
    True
    >>> isinstance(row[1],numbers.Real)
    True
    >>> isinstance(row[2],str)
    True
    '''
    cursor=connect.cursor()
    try:
        cursor.execute(sqlstring)
        rows = cursor.fetchall()
    except :
        logging.error("数据库进行sql查寻时出错")
        raise
    finally:
        connect.close()
    return rows # 返回引用,注意防止修改

def drawtext(x=None,y=None,text='什么都没有',draw=None,size=50):
    '''
    @brief 在cad里输入文字。
    >>> drawtext(x=36395514.9324,y=3250445.33498,text=r'\A1;T{\H0.7x;\S^3;}x',draw=getdrawscript('D:\\Drawing11.dwg')) == 0
    True
    '''
    if isinstance(x,numbers.Real) and isinstance(y,numbers.Real) and text: #无文字则不绘
        point=array.array('d',[x,y,0])
        try:
            ms=draw.ModelSpace #draw必须没有关闭
            #draw.ModelSpace.AddText(text,point,size) #单行文本
            ms.AddMText(point,size,text) #多行文本
        except:
            logging.error("绘制文字出错!")
            logging.error("\nx:%s\ny:%s\ntext:%s\npoint:%s\ndraw:%s\nms:\s"%(x,y,text,point,draw,ms))
            draw.Application.Quit()
            raise
        return 0
    return 1

def removesharp(text):
    '''
    @brief 去掉text中的表示supermap标签专题图上下标的特殊符号
    >>> removesharp("T#-3#=x")
    'T3x'
    >>> removesharp("J#-2#=S#+2")
    'J2S2'
    >>> removesharp("")
    ''
    >>> removesharp(None)
    ''
    '''
    if text:
        sharppattern=re.compile(r'#[+-=]')
        modifiedtext=sharppattern.sub(r"",text,count=0)
    else:
        modifiedtext=""
    return modifiedtext

def addchinesenote(test):
    pass


def sharp2mtext(text):
    '''
    >>> text1 = 'T#-3#=x'
    >>> text2 = 'J#-2#=S#+2'
    >>> text3 = None
    >>> sharp2mtext(text1) == '\\A1;T{\H0.7x;\\\\S^3;}x'
    True
    >>> #注意这是用的是repr()函数输出。
    >>> print sharp2mtext(text1)
    \A1;T{\H0.7x;\\S^3;}x
    >>> sharp2mtext(text2) == '\\A1;J{\H0.7x;\\S^2;}S{\H0.7x;\\S2^;}'
    True
    >>> sharp2mtext(text3) == ''
    True
    '''
    if not text:
        return ''
    else:
        ws=text.split('#')
        logging.info(ws)
        ws_conved=[]
        for w in ws[1:]:
            w_tem=''
            if w[0] == '+':
                w_tem = r'{\H0.7x;\S' + w[1:] + r'^;}'
            elif w[0] == '-':
                w_tem = r'{\H0.7x;\S^' + w[1:] + r';}'
            elif w[0] == '=':
                w_tem = w[1:]
            ws_conved.append(w_tem)
        text_conved = r'\A1;'+ws[0]+''.join(ws_conved)
        return text_conved

def main(*args,**kargs):
    '''
    >>> #main(filename="D:\\Drawing1.dwg",sqlstring="SELECT SmX,SmY,name FROM SMDTV_93")
    0
    >>> # main(filename="D:\\Drawing2.dwg",sqlstring="SELECT SmX,SmY,name FROM SMDTV_93") 失败,由于Drawing2.dwg还不存在
    >>> # 0
    >>> config = ConfigParser.ConfigParser()
    >>> config.read('dot2text.cfg')
    ['dot2text.cfg']
    >>> connectstring = config.get('APPLICATION','connectstring')
    >>> connectstring='DRIVER={SQL SERVER};SERVER=LUOBO\\SQLEXPRESS;DATABASE=chengguuo'
    >>> filename = config.get('APPLICATION','outputfile')
    >>> sqlstring = config.get('APPLICATION','sqlstring')
    >>> dbtype =config.get('APPLICATION','dbtype')
    >>> main(filename=filename,sqlstring=sqlstring,dbtype=dbtype,connectstring=connectstring)
    0
    '''
    try:
        filename=kargs['filename']
        sqlstring=kargs['sqlstring']
        dbtype=kargs['dbtype']
        connectstring=kargs['connectstring']
    except:
        logging.info("请给出正确的关键字参数")
        return 1
    if not filename:
        draw=getdrawscript()
    else:
        draw=getdrawscript(filename)

    try:
        layer=draw.Layers.Add("DOT_2_TEXT") #新增图层
        draw.ActiveLayer=layer
    except :
        logging.error("添加新图层出错")
        draw.Application.Quit()
        raise
    # 这里出过大bug,主要是异常的处理
    #try:
    #    dbconnect=getconnect(db_type=dbtype,db_arg=connectstring)
    #except:
    #    raise
    #finally:
    #    draw.Application.Quit()
    try:
        dbconnect=getconnect(db_type=dbtype,db_arg=connectstring)
    except:
        draw.Application.Quit()
        raise
    try:
        rows=getrows(sqlstring,dbconnect)
    except:
        return 1
    try:
        for row in rows:
            #drawtext(x=row[0],y=row[1],text=removesharp(row[2]),draw=draw)
            drawtext(x=row[0],y=row[1],text=sharp2mtext(row[2]),draw=draw)
        draw.save()
    except:
        logging.error("主函数中的drawtext操作出错")
        logging.error("drawtext:\nrow[0]:%s\nrow[1]:%s\nrow[2]:%s\n"%(row[0],row[1],row[2]))
        return 1
    draw.Application.Quit()
    return 0

if __name__ == "__main__":
    #filename = raw_input("请输入文件名\n") # D:\Drawing1.dwg
    #sqlstring = raw_input("***请不要误操作!***\n请输入查询语句。\n") # select SmX,SmY,name from SMDTV93
    config = ConfigParser.ConfigParser()
    config.read('dot2text.cfg')
    connectstring = config.get('APPLICATION','connectstring')
    filename = config.get('APPLICATION','outputfile')
    sqlstring = config.get('APPLICATION','sqlstring')
    dbtype =config.get('APPLICATION','dbtype')
    main(filename=filename,sqlstring=sqlstring,dbtype=dbtype,connectstring=connectstring)
Avatar_small
seo service UK 说:
2024年8月21日 17:34

A very popular gaming site with very entertaining games, as well as having lots of bonus features and promotions on offer. The lottery game has the biggest prizes, come try your luck. Don’t miss out. For more complete information, visit the website

Avatar_small
here 说:
2024年8月21日 17:59

We are a family owned and operated house cleaning services Worcester. We offer a wide range of house cleaning services to fit your needs and budget, including janitorial services in Massachusetts, deep cleaning, move-in/move-out cleaning, and more. Dec Master Cleaning are licensed and insured, and our team of experienced and reliable cleaners will leave your home clean and sparkling every time.

Avatar_small
사설토토 说:
2024年8月21日 18:00

I want your approach of inscription. cheers for taking the time to speak about this! Thanks over and over! Notable, an amazing article that i virtually enjoyed. Furthermore kurt russell christmas coat, i cannot help thinking about why i did not peruse it earlier. I remain tuned and aware of the subsequent

Avatar_small
here 说:
2024年8月21日 18:01

Dewapoker adalah situs judi poker online terpercaya di Asia. Situs ini memberikan bonus pada setiap harinya. Situs ini sering mengadakan event berhadiah yang dapat Anda dapatkan.

Avatar_small
get more info 说:
2024年8月21日 18:02

I recently came across your article and have article.I will make sure to be reading your blog more. You made a good point but I can't help but wonder, what about the other side?

Avatar_small
information 说:
2024年8月21日 18:03

Wonderful beat ! I wish to apprentice while you amend your web site, how could i subscribe for a blog website? The account aided me a acceptable deal. I had been a little bit acquainted of this your broadcast offered bright clear idea

Avatar_small
good data 说:
2024年8月21日 18:04

hi, i do think your web page nicely. 

Avatar_small
Find out 说:
2024年8月21日 18:05

I had not discovered such a solution like this. I am able to at this moment relish my future. Thanks for your time so much for this reliable and effective guide. I won’t hesitate to suggest your web blog to any individual who ought to have tips on this area. 

Avatar_small
토랜드 说:
2024年8月21日 18:06

There've been highs and lows, wins and losses, but through it all, I've been learnin' and growin', figurin' out what it takes to make a profit in them there markets. And when I see them profits start to roll in, well, it's like findin' water in the desert! So here's to many more adventures on this here site, where the games are wild, and the investments are ripe for the pickin'!

Avatar_small
website 说:
2024年8月21日 18:07

Have you ever heard of Sports Toto? Simply put, you can think of it as a betting game using sports events. We will tell you about a Toto site recommendation specialized eating and running verification site that can help sports betting with a fun and pleasant system. thank you

Avatar_small
website 说:
2024年8月21日 18:09

Thick, fabric materials are likewise utilized in light of their delicate properties ideal for ladies who are searching for shoes that are delicate and agreeable to the feet.

Avatar_small
information 说:
2024年8月21日 18:09

Do you think you can hold your own amongst sneaker collectors and call out a fake Off-White x Air Jordan 4 SP Sail when you see one? Definitely no! So, others are the same as you. Never mind wearing Fake Shoes, you are saving money for yourself!

Avatar_small
reference material 说:
2024年8月21日 18:12

I would like to thank you for the efforts you have made in writing this article. I am hoping the same best work from you in the future as well. In fact your creative writing abilities has inspired me to start my own Blog Engine blog now. Really the blogging is spreading its wings rapidly. Your write up is a fine example of it

Avatar_small
click here 说:
2024年8月21日 18:17

Poker88 adalah situs poker online yang paling banyak diminati hingga kini. Situs Ini menyajikan berbagai permainan yang menarik yang membuat para penjudi online dari situs lain beralih kesini. situs ini memberikan layanan dan keamanan tercanggih untuk menghindari kecurangan ataupu perilaku hacker. segera gabung di situs ini dan dapatkan jackpotnya disini

Avatar_small
토토사이트실험실 说:
2024年8月21日 18:18

Your post is very helpful to get some effective tips to reduce weight properly. You have shared various nice photos of the same. I would like to thank you for sharing these tips. Surely I will try this at home. Keep updating more simple tips like this. Interesting topic for a blog. I have been searching the Internet for fun and came upon your website. Fabulous post. Thanks a ton for sharing your knowledge! It is great to see that some people still put in an effort into managing their websites. I’ll be sure to check back again real soon. 

Avatar_small
casinosesang 说:
2024年8月21日 18:52

Dewabet adalah situs poker online yang paling banyak diminati hingga kini. Situs Ini menyajikan berbagai permainan yang menarik yang membuat para penjudi online dari situs lain beralih kesini. situs ini memberikan layanan dan keamanan tercanggih untuk menghindari kecurangan ataupu perilaku hacker. segera gabung dii situs ini dan dapatkan jackpotnya

Avatar_small
website 说:
2024年8月21日 18:53

Wonderful beat ! I wish to apprentice while you amend your web site, how could i subscribe for a blog website? The account aided me a acceptable deal. I had been a little bit acquainted of this your broadcast offered bright clear idea

Avatar_small
카공 说:
2024年8月21日 18:55

in addition to the content material! Hi there! I may want to have sworn i’ve visited this weblog before but after surfing via a number of the posts i realized it’s new to me. Nonetheless, i’m actually glad i got here across it and i’ll be e book-marking it and checking lower back frequently! Well i’m not writing all that over again. Anyways, simply wanted to mention high-quality weblog!

Avatar_small
information 说:
2024年8月21日 18:55

ave been browsing on-line greater than 3 hours lately, but I by no means discovered any interesting article like yours. It is beautiful price sufficient for me. In my opinion, if all web owners and bloggers made excellent content material as you did, the net will be a lot more useful than ever before. absolutely much like your web page nevertheless, you need to examine the transliteration on a good number of of one's content. Several of options filled by using transliteration issues so i to get them pretty troublesome to tell the truth then again I most certainly will unquestionably return all over again. whoah this weblog is excellent i like reading your articles. Keep up the good work! You already know, lots of persons are looking around for this information, you can aid them greatly.

Avatar_small
get more info 说:
2024年8月21日 18:58

This is my first visit to your web journal! We are a group of volunteers and new activities in the same specialty. Website gave us helpful data to work.

Avatar_small
check here 说:
2024年8月21日 18:59

ave been browsing on-line greater than 3 hours lately, but I by no means discovered any interesting article like yours. It is beautiful price sufficient for me. In my opinion, if all web owners and bloggers made excellent content material as you did, the net will be a lot more useful than ever before. absolutely much like your web page nevertheless, you need to examine the transliteration on a good number of of one's content. Several of options filled by using transliteration issues so i to get them pretty troublesome to tell the truth then again I most certainly will unquestionably return all over again. whoah this weblog is excellent i like reading your articles. Keep up the good work! You already know, lots of persons are looking around for this information, you can aid them greatly.

Avatar_small
thebrennanhouse 说:
2024年8月21日 19:02

after i initially commented i appear to have clicked at the -notify me when new remarks are added- checkbox and now on every occasion a remark is delivered i receive 4 emails with the same remark. There must be an easy technique you can get rid of me from that carrier? Thank you! What i don’t understood is clearly how you’re now not truly tons more nicely-preferred than you'll be now. You’re very wise. You understand therefore drastically in terms of this concern, produced me in my opinion believe it from such a lot of diverse angles. Its like males and females aren't involved except it's miles one factor to do with girl gaga! Your man or woman stuffs splendid. Always take care of it up!

Avatar_small
good contents 说:
2024年8月21日 19:02

I as well believe thence , perfectly pent post! Youre so cool! I dont suppose Ive read something such as this before. So nice to seek out somebody by incorporating authentic ideas on this subject. realy i appreciate you for starting this up. this excellent website are some things that’s needed online, somebody after a little bit originality. helpful work for bringing something new to the web! You really should take part in a tournament for starters of the best blogs on-line. I am going to recommend this great site! Nice post! This is a very nice blog that I will definitively come back to more times this year! Thanks for informative post.


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter