Best Python code snippet using websmith_python
zpm_report_mwo.py
Source:zpm_report_mwo.py  
1# -*- coding: utf-8 -*-2"""3Created on Thu Dec 24 18:29:45 20204@author: C481425"""6#-Begin------------------------------------------------------------------------7#-Includes---------------------------------------------------------------------8import sys, win32com.client9import os10#-Sub -------------------------------------------------------------------------11def zpm_report_mwo_id(fecha_desde, fecha_hasta, directorio, nombre_fichero_woe):12   """ Extrae de SAP informe con los datos necesarios para INFORME DIARIO13   14   Usa la transacción ZPM_REPORT_MWO, con los datos de fecha inicio y fecha15   final para las OT de MC y del centro emplazamiento 2013.16   Los datos los extrae a través del icono de excel situado en SAP, en la 17   ubicación pasada como parámetro y con el nombre del fichero (sin extensión)18   también pasado como parámetro.19   20   Parámetros:21   -----------22   fecha_desde : str, con el formato DD.MM.AAAA23   24   fecha_hasta : str, con el formato DD.MM.AAAA25   26   directorio  : str, path del directorio de destino del fichero27   28   nombre_fichero_woe : str, nombre del fichero sin extensión.29   """30   try:31      SapGuiAuto = win32com.client.GetObject("SAPGUI")32      if not type(SapGuiAuto) == win32com.client.CDispatch:33         return34      application = SapGuiAuto.GetScriptingEngine35      if not type(application) == win32com.client.CDispatch:36         SapGuiAuto = None37         return38      connection = application.Children(0)39      if not type(connection) == win32com.client.CDispatch:40         application = None41         SapGuiAuto = None42         return43      session = connection.Children(0)44      if not type(session) == win32com.client.CDispatch:45         connection = None46         application = None47         SapGuiAuto = None48         return49      50      #session.findById("wnd[0]").maximize()51      session.findById("wnd[0]/tbar[0]/okcd").text = "ZPM_REPORT_MWO"52      session.findById("wnd[0]").sendVKey(0)53      # Check box --> Pendiente [True|False]54      session.findById("wnd[0]/usr/chkDY_OFN").selected = True55      # Check box --> En tratam. [True|False]56      session.findById("wnd[0]/usr/chkDY_IAR").selected = True57      # Check box --> Concluido [True|False]58      session.findById("wnd[0]/usr/chkDY_MAB").selected = True59      session.findById("wnd[0]/usr/ctxtAUART-LOW").text = "MC"60      session.findById("wnd[0]/usr/ctxtDATUV").text = fecha_desde61      session.findById("wnd[0]/usr/ctxtDATUB").text = fecha_hasta62      session.findById("wnd[0]/usr/ctxtSWERK-LOW").text = "2013"63      session.findById("wnd[0]/usr/ctxtSWERK-LOW").setFocus()64      session.findById("wnd[0]/usr/ctxtSWERK-LOW").caretPosition = 465      session.findById("wnd[0]").sendVKey(0)66      session.findById("wnd[0]/tbar[1]/btn[8]").press()         # Ejecutar trans.67      session.findById("wnd[0]/tbar[1]/btn[20]").press()        # Botón fic.excel68      session.findById("wnd[1]/usr/ctxtD_RUTA").text = \69                      (directorio + nombre_fichero_woe)70      session.findById("wnd[1]/usr/ctxtD_RUTA").caretPosition = 771      if os.path.isfile(directorio + nombre_fichero_woe + ".csv"):72         os.remove(directorio + nombre_fichero_woe + ".csv")73      session.findById("wnd[1]/usr/btnBUTTON_DESCARGA").press()74      session.findById("wnd[0]/tbar[0]/btn[15]").press()75      session.findById("wnd[0]/tbar[0]/btn[15]").press()76   except:77      print(sys.exc_info()[0])78   finally:79      session = None80      connection = None81      application = None82      SapGuiAuto = None83#------------------------------------------------------------------------------84def zpm_report_mwo_hot(clase_orden,\85                       fecha_entrada_desde,\86                       fecha_entrada_hasta,\87                       variante,\88                       path,\89                       file_name_woe):90    """Extrae de SAP los datos de Historico de Ot's para cálculos de eficiencia91    92    Detallar la información.93    """94    95    try:96        SapGuiAuto = win32com.client.GetObject("SAPGUI")97        if not type(SapGuiAuto) == win32com.client.CDispatch:98            return99        100        application = SapGuiAuto.GetScriptingEngine101        if not type(application) == win32com.client.CDispatch:102            SapGuiAuto = None103            return104        105        connection = application.Children(0)106        if not type(connection) == win32com.client.CDispatch:107            application = None108            SapGuiAuto = None109            return110        111        session = connection.Children(0)112        if not type(session) == win32com.client.CDispatch:113            connection = None114            application = None115            SapGuiAuto = None116            return117        #session.findById("wnd[0]").maximize()118        session.findById("wnd[0]/tbar[0]/okcd").text = "ZPM_REPORT_MWO"119        session.findById("wnd[0]").sendVKey(0)120        # Check box --> Pendiente [True|False]121        session.findById("wnd[0]/usr/chkDY_OFN").selected = True122        # Check box --> En tratam. [True|False]123        session.findById("wnd[0]/usr/chkDY_IAR").selected = True124        # Check box --> Concluido [True|False]125        session.findById("wnd[0]/usr/chkDY_MAB").selected = True126        # Clase Orden127        session.findById("wnd[0]/usr/ctxtAUART-LOW").text = clase_orden128        # Fecha periodo desde en blanco129        session.findById("wnd[0]/usr/ctxtDATUV").text = ""130        # Fecha periodo hasta en blanco131        session.findById("wnd[0]/usr/ctxtDATUB").text = ""132        # Fecha entrada Ot desde133        session.findById("wnd[0]/usr/ctxtERDAT-LOW").text = fecha_entrada_desde134        # Fecha entrada Ot hasta135        session.findById("wnd[0]/usr/ctxtERDAT-HIGH").text = fecha_entrada_hasta136        # Centro Emplazamiento137        session.findById("wnd[0]/usr/ctxtSWERK-LOW").text = "2013"138        # Selección Variante139        session.findById("wnd[0]/usr/ctxtVARIANT").text = variante140        session.findById("wnd[0]/usr/ctxtVARIANT").setFocus()141        session.findById("wnd[0]/usr/ctxtVARIANT").caretPosition = 12142        session.findById("wnd[0]/tbar[1]/btn[8]").press()143        session.findById("wnd[0]/mbar/menu[0]/menu[11]/menu[2]").select()144        session.findById("wnd[1]/tbar[0]/btn[0]").press()145        session.findById("wnd[1]/usr/ctxtRLGRAP-FILENAME").text = path + file_name_woe + '.txt'146        session.findById("wnd[1]/usr/ctxtRLGRAP-FILENAME").caretPosition = 49147        if os.path.isfile(path + file_name_woe + '.txt'):148            session.findById("wnd[1]/tbar[0]/btn[0]").press()149        session.findById("wnd[1]/tbar[0]/btn[0]").press()150        session.findById("wnd[0]/tbar[0]/btn[15]").press()151        session.findById("wnd[0]/tbar[0]/btn[15]").press()152      153    except:154        print(sys.exc_info()[0])155    finally:156        session = None157        connection = None158        application = None159        SapGuiAuto = None...SAPApplication.py
Source:SAPApplication.py  
1import win32com.client2import uiautomation as ua3import subprocess, win32gui, time4import pywintypes5class SAPApplication:6    def OpenSAP(self):7        sap_app = r"C:\Program Files (x86)\SAP\FrontEnd\SAPgui\saplogon.exe"8        subprocess.Popen(sap_app)9    def Connect2SAP_API(self):10        SapGuiAuto = win32com.client.GetObject("SAPGUI")11        if not type(SapGuiAuto) == win32com.client.CDispatch:12            return False13        application = SapGuiAuto.GetScriptingEngine14        if not type(application) == win32com.client.CDispatch:15            SapGuiAuto = None16            return 017        connection = application.Children(0)18        if not type(connection) == win32com.client.CDispatch:19            application = None20            SapGuiAuto = None21            return 022        flag = 023        while flag == 0:24            try:25                session = connection.Children(0)26                flag = 127            except:28                time.sleep(0.5)29        if not type(session) == win32com.client.CDispatch:30            connection = None31            application = None32            SapGuiAuto = None33            return 034        return session35    def LogInMenu(self):36        saplogonHwnd = 037        while saplogonHwnd == 0:38            saplogonHwnd = win32gui.FindWindow("#32770", "SAP Logon 740")  # åå©spy++å·¥å
·æåå¾å°å
¶ç±»å#32770ï¼åçªå£æ é¢SAP Logon 74039            time.sleep(0.1)40        '''妿æ
å¿å¥ææè·å°åï¼sapçé¢ä¾ç¶æ²¡å è½½å¥½ï¼å¯ä»¥ä½¿ç¨IsWindowVisibleè¿ä¸æ¥ç¡®è®¤ï¼ç´è³çªå£å¯è§'''41        visibleFlag = False42        while visibleFlag == False:43            time.sleep(0.1)44            visibleFlag = win32gui.IsWindowVisible(saplogonHwnd)45        sapLogonDialog = ua.WindowControl(searchDepth=2, Name='SAP Logon 740')46        testControl = sapLogonDialog.Control(searchDepth=12, Name='T01 [HQ_PRODUCTION]')47        testControl.DoubleClick()48    49    def WindowResize(self, session):50        session.findById("wnd[0]").resizeWorkingPane(164, 36, 0)51    52    def LogInUser(self, session):53        session.findById("wnd[0]/usr/tblSAPMSYSTTC_IUSRACL/btnIUSRACL-BNAME[1,1]").setFocus()54        session.findById("wnd[0]/usr/tblSAPMSYSTTC_IUSRACL/btnIUSRACL-BNAME[1,1]").press()55    56    def DownloadSpecs(self, session, part_no):57        if not session:58            return 'API connect wrongly'59        try:60            self._DownloadSpecs(session, part_no)61        except pywintypes.com_error:62            error_msg = session.findById('/app/con[0]/ses[0]/wnd[0]/sbar/pane[0]').text63            session.findById("wnd[0]").close()64            session.findById("wnd[1]/usr/btnSPOP-OPTION1").press()65            return error_msg66    def _DownloadSpecs(self, session, part_no):67        session.findById("wnd[0]").sendVKey(0)68        session.findById("wnd[0]/tbar[0]/okcd").text = "MM03"69        session.findById("wnd[0]").sendVKey(0)70        session.findById("wnd[0]/usr/ctxtRMMG1-MATNR").text = part_no71        session.findById("wnd[0]/usr/ctxtRMMG1-MATNR").caretPosition = 1272        session.findById("wnd[0]").sendVKey(0)73        session.findById("wnd[1]/usr/tblSAPLMGMMTC_VIEW").getAbsoluteRow(0).selected = -174        session.findById("wnd[1]/tbar[0]/btn[0]").press()75        session.findById("wnd[0]/mbar/menu[4]/menu[6]").select()76        groupMembers = session.ActiveWindow.findAllByName("DRAW-DOKAR", "")77        ROH_ID = ''78        for groupMember in groupMembers:79            if groupMember.text.startswith("ROH"):80                ROH_ID = groupMember.id81                break82        while not ROH_ID:83            ROH_ID = self.ScrollAndFind(session, "DRAW-DOKAR", '')84        groupMembers = session.ActiveWindow.findAllByName("DRAW-DOKAR", "")85        for groupMember in groupMembers:86            if groupMember.text.startswith("ROH"):87                ROH_ID = groupMember.id88                break89        session.findById(ROH_ID).setFocus()90        session.findById(ROH_ID).caretPosition = 091        session.findById("wnd[1]/usr/subSCREEN:SAPLCV140:0204/subDOC_ALV:SAPLCV140:0207/btnX4").press()92        session.findById("wnd[1]/tbar[0]/btn[12]").press()93        session.findById("wnd[0]/tbar[0]/btn[15]").press()94        session.findById("wnd[0]/tbar[0]/btn[15]").press()95        session.findById("wnd[1]/usr/btnSPOP-OPTION1").press()96    def ScrollAndFind(self, session, name, label):97        session.findById(98            "wnd[1]/usr/subSCREEN:SAPLCV140:0204/subDOC_ALV:SAPLCV140:0207/tblSAPLCV140SUB_DOC").verticalScrollbar.position = 399        groupMembers = session.ActiveWindow.findAllByName(name, label)100        for groupMember in groupMembers:101            if groupMember.text.startswith("ROH"):102                ROH_ID = groupMember.id103                return ROH_ID104        return False105    def DownloadBOMForm(self, session,part_no):106        if not session:107            return 'API connect wrongly'108        try:109            self._DownloadBOMForm(session, part_no)110        except pywintypes.com_error:111            error_msg = session.findById('/app/con[0]/ses[0]/wnd[0]/sbar/pane[0]').text112            session.findById("wnd[0]").close()113            session.findById("wnd[1]/usr/btnSPOP-OPTION1").press()114            return error_msg115    def _DownloadBOMForm(self, session, part_no):116        session.findById("wnd[0]/tbar[0]/okcd").text = "YP43"117        session.findById("wnd[0]").sendVKey(0)118        session.findById("wnd[0]/usr/ctxtP_MATNR").text = part_no119        session.findById("wnd[0]/usr/ctxtP_MATNR").setFocus()120        session.findById("wnd[0]/usr/ctxtP_MATNR").caretPosition = 12121        session.findById("wnd[0]").resizeWorkingPane(164, 36, 0)122        session.findById("wnd[0]/usr/btn%_S_PREFIX_%_APP_%-VALU_PUSH").press()123        session.findById("wnd[1]/tbar[0]/btn[16]").press()124        session.findById("wnd[1]/tbar[0]/btn[8]").press()125        session.findById("wnd[0]/tbar[1]/btn[8]").press()126        session.findById("wnd[0]/mbar/menu[0]/menu[1]/menu[2]").select()127        session.findById(128            "wnd[1]/usr/subSUBSCREEN_STEPLOOP:SAPLSPO5:0150/sub:SAPLSPO5:0150/radSPOPLI-SELFLAG[1,0]").select()129        session.findById(130            "wnd[1]/usr/subSUBSCREEN_STEPLOOP:SAPLSPO5:0150/sub:SAPLSPO5:0150/radSPOPLI-SELFLAG[1,0]").setFocus()131        session.findById("wnd[1]/tbar[0]/btn[0]").press()132        session.findById("wnd[1]/usr/ctxtDY_FILENAME").text = '{}.xls'.format(part_no)133        session.findById("wnd[1]/usr/ctxtDY_FILENAME").caretPosition = 16134        session.findById("wnd[1]/tbar[0]/btn[11]").press()135        session.findById("wnd[0]/tbar[0]/btn[15]").press()136        session.findById("wnd[0]/tbar[0]/btn[15]").press()137if __name__=='__main__':138    ...untitled.py
Source:untitled.py  
1import subprocess2password = 'PCT4life!'3start_date = '01/01/2003'4batch_dir = 'Z:\\Data Analytics\\0. Projects\\Fleet Smooth Replacement Plan\\data\\batch\\'5output_dir = 'C:\\Users\\bvanderblock\\Desktop'6batch_name = 'fleet_vehicles_batch_1.csv'7file_name = 'export-test-2.XLSX'8subprocess.call(['cscript.exe', '''9If Not IsObject(application) Then10   Set SapGuiAuto  = GetObject("SAPGUI")11   Set application = SapGuiAuto.GetScriptingEngine12End If13If Not IsObject(connection) Then14   Set connection = application.Children(0)15End If16If Not IsObject(session) Then17   Set session    = connection.Children(0)18End If19If IsObject(WScript) Then20   WScript.ConnectObject session,     "on"21   WScript.ConnectObject application, "on"22End If23session.findById("wnd[0]").maximize24session.findById("wnd[0]/usr/txtRSYST-BNAME").text = "bvanderblock"25session.findById("wnd[0]/usr/pwdRSYST-BCODE").text = "'''26+27password28+29'''"30session.findById("wnd[0]/usr/pwdRSYST-BCODE").setFocus31session.findById("wnd[0]/usr/pwdRSYST-BCODE").caretPosition = 932session.findById("wnd[0]").sendVKey 033session.findById("wnd[0]/usr/cntlIMAGE_CONTAINER/shellcont/shell/shellcont[0]/shell").expandNode "F00003"34session.findById("wnd[0]/usr/cntlIMAGE_CONTAINER/shellcont/shell/shellcont[0]/shell").selectedNode = "F00006"35session.findById("wnd[0]/usr/cntlIMAGE_CONTAINER/shellcont/shell/shellcont[0]/shell").topNode = "Favo"36session.findById("wnd[0]/usr/cntlIMAGE_CONTAINER/shellcont/shell/shellcont[0]/shell").doubleClickNode "F00006"37session.findById("wnd[1]").sendVKey 438session.findById("wnd[2]/usr/lbl[1,7]").setFocus39session.findById("wnd[2]/usr/lbl[1,7]").caretPosition = 140session.findById("wnd[2]/tbar[0]/btn[0]").press41session.findById("wnd[1]/tbar[0]/btn[0]").press42session.findById("wnd[0]/usr/ctxtR_BUDAT-LOW").text = "'''43+44start_date45+46'''"47session.findById("wnd[0]/usr/ctxtAUFNR-LOW").setFocus48session.findById("wnd[0]/usr/ctxtAUFNR-LOW").caretPosition = 049session.findById("wnd[0]/usr/btn%_AUFNR_%_APP_%-VALU_PUSH").press50session.findById("wnd[1]/tbar[0]/btn[23]").press51session.findById("wnd[2]/usr/ctxtDY_PATH").text = "'''52+53batch_dir54+55'''"56session.findById("wnd[2]/usr/ctxtDY_FILENAME").text = "'''57+58batch_name59+60'''"61session.findById("wnd[2]/usr/ctxtDY_FILENAME").caretPosition = 2662session.findById("wnd[2]/tbar[0]/btn[0]").press63session.findById("wnd[1]/tbar[0]/btn[8]").press64session.findById("wnd[0]/tbar[1]/btn[8]").press65session.findById("wnd[0]/tbar[1]/btn[43]").press66session.findById("wnd[1]/usr/ctxtDY_PATH").text = "'''67+68output_dir69+70'''"71session.findById("wnd[1]/usr/ctxtDY_FILENAME").text = "'''72+73file_name74+75'''"...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
