1. 程式人生 > >利用python的圖形介面實現一些小工具

利用python的圖形介面實現一些小工具

import easygui as g
import sys
import datetime
import uuid
import socket
import psycopg2
import uuid

nowTime=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')#現在
values = []

執行人和執行需求的視窗

def per_message():
    fields = ['*使用者名稱', '*需求單號']
    msg = '填寫下面資訊(*為必填項)'
    title = '執行人資訊'
    fieldvalue = g.multenterbox(msg, title, fields)
    while
True: if fieldvalue == None: break errmsg = '' for item in range(len(fields)): option = fields[item].strip() if fieldvalue[item].strip() == "" and option[0] == "*": errmsg += ('[%s]為必填項。\n\n' % fields[item]) if errmsg == ''
: break fieldvalue = g.multenterbox(errmsg, title, fields, fieldvalue) if fieldvalue == None: return 'cancel' else: per_name = fieldvalue[0] per_request = fieldvalue[1] values.append(per_name) values.append(per_request) return
'ok'

執行指令碼的視窗

def runscript():
    msg = '把要執行的sql指令碼寫在下面'
    title = '執行指令碼!'
    text = ''
    script = g.codebox(msg, title, text)
    while script == None or script == '\n' or script == '':
        g.msgbox('沒有任何指令碼寫入!請寫入指令碼!!!')
        script = g.codebox(msg, title, text)
    values.append(script)

獲取mac地址

def get_mac_address():
    mac=uuid.UUID(int = uuid.getnode()).hex[-12:]
    mac_adr = ":".join([mac[e:e+2] for e in range(0,11,2)])
    values.append(mac_adr)

獲取ip和計算機名稱

def get_ipadrr():
    #獲取本機電腦名
    computer_name = socket.getfqdn(socket.gethostname( ))
    #獲取本機ip
    ip_addr = socket.gethostbyname(computer_name)
    values.append(computer_name)
    values.append(ip_addr)

寫入txt檔案

def writeintext(writein):
        # 將指令碼存放起來
        writeintxt = open('account.txt', 'a+',encoding="utf-8")
        writeintxt.write(writein + '/' + nowTime + '\n')
        writeintxt.close()

用來操作資料庫的類

class GPCommand(object):
    # 類的初始化
    def __init__(self):
      self.hostname = '10.1.2.xxx'
      self.username = 'appxxx'
      self.password = 'xxxx'
      self.database = 'gsdw'
    def connectGp(self):
      try:
        #連結資料庫
        #讀取配置利用connect連結資料庫
        self.connect = psycopg2.connect( host=self.hostname, user=self.username, password=self.password, dbname=self.database )
        #建立一個新的cursor
        self.cursor = self.connect.cursor()
        print("connect gp successful")
      except:
        print('connect gp error.')
    def insertData(self,my_dict):
        try:
            id = my_dict['id']
            per_name = my_dict['per_name']
            per_request = my_dict['per_request']
            script = ''
            script_tmp = my_dict['script']
            if "'" in script_tmp:
                nops = []
                new_loop = []
                itemplist = list(script_tmp)
                for i in range(len(itemplist)):
                    if itemplist[i] == "'":
                        nops.append(i)
                for item in nops:
                    new_loop.append(item + nops.index(item))
                for i in new_loop:
                    itemplist.insert(i, "'")
                script = "".join(itemplist)
            else:
                script = script_tmp
            mac_adr = my_dict['mac_adr']
            computer_name = my_dict['computer_name']
            ip_addr = my_dict['ip_addr']
            insertsql = "INSERT INTO dw_edw.edw_pub_log_database_change (id,per_name,per_request,script,mac_adr,computer_name,ip_addr,load_dt) values('%s','%s','%s','%s','%s','%s','%s',now()) " % (id,per_name,per_request,script,mac_adr,computer_name,ip_addr)
            self.cursor.execute(insertsql)
            self.connect.commit()
            return 'insert_success'
        except psycopg2.Error:
            error = 'Failed to setup Postgres environment.\n{0}'.format(sys.exc_info())
            return 'insert_failed' + error

    def execscript(self,my_dict):
        id = my_dict['id']
        execscript = my_dict['script']
        try:
            self.cursor.execute(execscript)
            self.connect.commit()
            #更新執行結果
            updatesql = "update dw_edw.edw_pub_log_database_change  set result = 'Y' where id = '%s' " %(id)
            self.cursor.execute(updatesql)
            self.connect.commit()
            print('執行成功')
            return 'exec_success'
        except psycopg2.Error:
            error = 'Failed to setup Postgres environment.\n{0}'.format(sys.exc_info())
            print('執行失敗')
            return 'exec_failed' + error
            #raise SystemExit(
            #print(error)
            #)

    #關閉資料庫
    def closeMysql(self):
        self.cursor.close()
        self.connect.close()
        print("資料庫已關閉")
def main():
    gpCommand = GPCommand()
    gpCommand.connectGp()
    per_result = per_message()
    if per_result == 'cancel':
        sys.exit(0)
    else:
        runscript()
        get_mac_address()
        get_ipadrr()

    #     # #寫入txt檔案
    #     # for item in values:
    #     #     writeintext(item)

    new_dict = {
        "id" : uuid.uuid1(),
        "per_name": values[0],
        "per_request": values[1],
        "script": values[2],
        "mac_adr": values[3],
        "computer_name": values[4],
        "ip_addr": values[5],
    }
    insert_result = gpCommand.insertData(new_dict)
    if insert_result == 'insert_success':
        #g.msgbox(msg='記錄已插入成功,正在執行指令碼……',title='請確認')
        exec_result =  gpCommand.execscript(new_dict)
        if exec_result == 'exec_success':
            g.msgbox(msg='執行成功',title='請確認')
        else:
            g.msgbox(msg='執行失敗,請在測試環境測試後再執行'+ '\n'+ exec_result ,title='請確認')

    else:
        g.msgbox(msg='插入失敗' + '\n' + insert_result)

    # 最後一定要要把資料關閉
    gpCommand.closeMysql()

main()`這裡寫程式碼片`