Jump to content

Recommended Posts

Hello mates.

I would like to share simple but very important function required durning code many *au3 files.

Such as function is used by a few scripts developers on forum but most of users waste a lot of time to make his functions/tool free from errors and bugs.

How is working?

This function do not check errors like Scite debugger. You can be able to make something like call exceptions in Python.

Think about this and think when you ran some code, no error but also do nothing. 0 information and you have to jump into own or other script to find out reason.

Function: Updated 2018-02-04, 08:47 (fixed AutoIt problem with dedection @ScriptName)

;==============================================================================================================================================================
; Function:         Exception ([ $sInfo = "" [, $vReturnValue = Null [, $vExtended = @extended [, $iErrorNr = @error [, $iErrorLine = @ScriptLineNumber ]]]]])
;
; Description:      Call exceptions in different *au3 files located in this same Folder.
;
; Parameter(s):     $sInfo -        Information about exception in code, created by yourself.
;                   $vReturnValue - (Default=Null) Set value to return durning exception.
;                   $iErrorNr -     (Default=@error) Set the error manually by adding a number.
;                   $vExtended -    (Default=@extended) Set extended manually.
;                   $iErrorLine -   Internal use do not change!
;
; Return Value(s):  $vReturnValue,
;                   Additional: Output string in Scite Console about debug trace.
;
; Author (s):       Who cares?
;==============================================================================================================================================================
Func Exception($sInfo="", $vReturnValue = Null, $iErrorLine = @ScriptLineNumber, $iErrorNr = @error, $vExtended = @extended)

    Dim $aArray[0]
    Local $sScriptPath = @ScriptFullPath
    Local $sCurrentScriptLine = StringLower(FileReadLine($sScriptPath, $iErrorLine))

    If Not StringInStr($sCurrentScriptLine, "exception") Then
        Local $aInclude = FileReadToArray($sScriptPath)
        For $sItem In $aInclude
            Local $sLowerLine = StringLower($sItem)
            If StringInStr($sLowerLine, "#include") Then
                Local $sIncludeName = StringTrimLeft($sItem, 8)
                Local $sConvertedName = ""
                Local $bAdd = False
                Local $aDelimeter = ["<", ">"]
                If StringInStr($sIncludeName , "'") Then
                    $aDelimeter[0] = "'"
                    $aDelimeter[1] = "'"
                ElseIf StringInStr($sIncludeName , '"') Then
                    $aDelimeter[0] = '"'
                    $aDelimeter[1] = '"'
                EndIf
                Local $aSplitInclude = StringSplit($sIncludeName, "")
                For $sSign In $aSplitInclude
                    If $sSign = $aDelimeter[0] And Not $bAdd Then
                        $bAdd = True
                        ContinueLoop
                    ElseIf $sSign = $aDelimeter[1] And $bAdd Then
                        ReDim $aArray[UBound($aArray) + 1]
                        $aArray[UBound($aArray) - 1] = $sConvertedName
                        ExitLoop
                    EndIf
                    If $bAdd Then $sConvertedName &= $sSign
                Next
            EndIf
        Next
    EndIf

    If UBound($aArray) > 0 Then
        For $sName In $aArray
            Local $sPath = @ScriptDir & "\" & $sName
            If FileExists($sPath) Then
                $sCurrentScriptLine = StringLower(FileReadLine($sPath, $iErrorLine))
                If StringInStr($sCurrentScriptLine, "exception") Then
                    $sScriptPath = $sPath
                    ExitLoop
                EndIf
            EndIf
        Next
    EndIf

    Local $aFile = FileReadToArray($sScriptPath)
    Local $sFunctionName, $sLine
    Local $bFound = False

    For $i = 0 To $iErrorLine - 1
        If $bFound Or $iErrorLine <= 0  Then ExitLoop
        $sLine = StringReplace($aFile[$iErrorLine - $i], @TAB, "")
        If StringInStr(StringLower($sLine), "func ") Then
            Local $aSortLine = StringSplit($sLine, '')
            $sLine = ""
            For $h = 1 To $aSortLine[0] - 1
                Local $sLowerSort = StringLower($aSortLine[$h])
                If $sLowerSort = "(" Then
                    $bFound = True
                    ExitLoop
                ElseIf $sLowerSort <> @TAB And $sLowerSort <> " " Then
                    If $sLowerSort = "f" Or $sLowerSort = "u" Or $sLowerSort = "n" Or $sLowerSort = "c" Then
                        $sLine &= $aSortLine[$h]
                    Else
                        If Not StringInStr($sLine, "func") Then
                            $sLine = ""
                            ExitLoop
                        Else
                            $sLine &= $aSortLine[$h]
                        EndIf
                    EndIf
                EndIf
            Next
        EndIf
    Next

    If StringLeft(StringLower($sLine), 4) <> "func" Then
        $sLine = ""
    EndIf

    $sFunctionName = StringTrimLeft($sLine, 4)

    If StringLen($sFunctionName) < 1 Then
        $sFunctionName = "not recognized"
    Else
        $sFunctionName &= " ( ... )"
    EndIf

    If StringLen($sInfo) < 1 Then
        $sInfo = "nothing about"
    EndIf

    $vRet = $vReturnValue

    If $vRet = Null Then
        $vRet = "Null"
    ElseIf IsArray($vRet) Then
        $vRet = "an Array with " & UBound($vRet) & " items"
    ElseIf IsBinary($vRet) Then
        $vRet = "binary " & $vRet
    ElseIf IsBool($vRet) Then
        $vRet = "bool " & $vRet
    ElseIf IsDllStruct($vRet) Then
        $vRet = "dll struct " & $vRet
    ElseIf IsFloat($vRet) Then
        $vRet = "float " & $vRet
    ElseIf IsHWnd($vRet) Then
        $vRet = "hwnd " & $vRet
    ElseIf IsInt($vRet) Then
        $vRet = "int " & $vRet
    ElseIf IsKeyword($vRet) Then
        $vRet = "keyword " & $vRet
    ElseIf IsNumber($vRet) Then
        $vRet = "number " & $vRet
    ElseIf IsObj($vRet) Then
        $vRet = "object " & $vRet
    ElseIf IsPtr($vRet) Then
        $vRet = "ptr " & $vRet
    ElseIf IsString($vRet) Then
        If $vReturnValue = "" or StringReplace($vRet, " ", "") = "" Then
            $vRet = 'empty string ""'
        Else
            $vRet = 'string "' & $vRet & '"'
        EndIf
    EndIf

    Local $sStruct
    $sStruct &= "! Exception = {" & @CRLF
    $sStruct &= "!" & @CRLF
    $sStruct &= "!" & @TAB & '"date" = ' & @YEAR & "-" & @MON & "-" & @MDAY & ", " & @HOUR & ":" & @MIN & ":" & @SEC & ", " & @MSEC & "ms," & @CRLF
    $sStruct &= "!" & @TAB & '"path" = ' & $sScriptPath & "," & @CRLF
    $sStruct &= "!" & @TAB & '"line" = ' & $iErrorLine & "," & @CRLF
    $sStruct &= "!" & @TAB & '"func" = ' & $sFunctionName & "," & @CRLF
    $sStruct &= "!" & @TAB & '"retn" = ' & $vRet & "," & @CRLF
    $sStruct &= "!" & @TAB & '"exten" = ' & $vExtended & "," & @CRLF
    $sStruct &= "!" & @TAB & '"error" = ' & $iErrorNr & "," & @CRLF
    $sStruct &= "!" & @TAB & '"info" = ' & $sInfo
    $sStruct &= @CRLF
    $sStruct &= "!" & @CRLF
    $sStruct &= "! }" & @CRLF & @CRLF

    ConsoleWrite($sStruct)

    Return $vReturnValue
EndFunc ;==> Exception

 

How to use? - Example 1

Func Example()
    Local $sFile = FileOpen(@ScriptDir & "\example.py")
    If $sFile = -1 Then
        Return Exception("Failed to open 'example.py', File not exist!")
    EndIf
    ; continue working
EndFunc

Example()

Example 1 Output in Scite console:

Exception 1.png

Example 2

Func Example2()
    Local $oHttp = ObjCreate("WinHttp.WinHttpRequest.5.1.Fake") ; added .Fake to make object wrong.
    If Not IsObj($oHttp) Then
        Return Exception("Failed to create Object in variable $oHttp.", 2.2)
    EndIf
    ; continue working
EndFunc

Local $vRet = Example2()

ConsoleWrite("$vRet = " & $vRet & @CRLF)

Example 2 Output in Scite console:

Exception 2.png

Edited by Ascer
Link to post
Share on other sites
  • 3 weeks later...

This is super! I normally do this through a message box or the like. Its kind of ironic that this type of error checking is almost always required, yet I had never thought to write a function to be used as the goto, instead opting to use Consolewrite and message boxes written at the time of error to figure out what value is being passed when something unexpected is being returned. This will go into my standard includes.
Thank you.

 

Edited by Draygoes
Spoiler

 

"If a vegetarian eats vegetables,What the heck does a humanitarian eat?"

"I hear voices in my head, but I ignore them and continue on killing."

"You have forced me to raise the indifference warning to beige, it's a beige alert people. As with all beige alerts please prepare to think about the possibility of caring."

An optimist says that giving someone power DOESN'T immediately turn them into a sadist. A pessimist says that giving someone power doesn't IMMEDIATELY turn them into a sadist.

 

 
Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By DanielRossinsky
      I've been working for quite a while on an automated installer for python3.8.3 and Thonny3.2.7 and encountered a pretty strange problem - automated python install work perfectly. However using pip to install esptool returns error code 1. The strange thing is if i manually install it after running the python installer it does indeed install correctly (returns 0 instead).
      The code i was using:
      Local Const $sInstallerPath = @ScriptDir & "\python-3.8.3.exe" Local $PythonResult = RunWait($sInstallerPath & " /quiet") Local $ESPToolResult = RunWait(@ComSpec & " /c " & "pip install esptool") MsgBox(0, "Installer returns", "Python result: " & $PythonResult & @CRLF & "esptool result: " & $ESPToolResult) Than I thought that maybe python installer fires off multiple processes during installation and tried :
      Local Const $sInstallerPath = @ScriptDir & "\python-3.8.3.exe" Local $iPID = Run($sInstallerPath & " /quiet") Local $PythonResult = ProcessWaitClose($iPID) Local $ESPToolResult = RunWait(@ComSpec & " /c " & "pip install esptool") MsgBox(0, "Installer returns", "Python result: " & $PythonResult & @CRLF & "esptool result: " & $ESPToolResult) However, The problem still remains. some-why esptool install refuses to be automated with python but if i comment out the python install part it does work ?! (note that i comment it out after the script already installed python and did not manually install it myself).
      Any idea why this happens ?
      NOTE: I added the unattend.xml file im using but python.exe was too big - I'm using python3.8.3 for compatibility with thonny and the unattend files makes a minimal install just for thonny to work (target platform esp32 with micopython)
      unattend.xml
    • By pete_wilde
      Hi Guys,
      I am trying to convert a python script to AutoIT, but it is not returning any data.

      My aim is to eventually have a script which sends me an email whenever a goal is scored in the English Premiership.
      Is there any guru who can have a quick look over the below script and see if there are any obvious errors?
      To use a football analogy, I think that I have hit the bar a couple of times, but not yet found the back of the net! 
      #cs ---------------------------------------------------------------------------- PYTHON CODE: import requests import json endpoint = "https://api.betfair.com/exchange/betting/rest/v1.0/" header = { 'X-Application' : 'APP_KEY_HERE', 'X-Authentication' : 'SESSION_TOKEN_HERE' ,'content-type' : 'application/json' } json_req='{"filter":{ }}' url = endpoint + "listEventTypes/" response = requests.post(url, data=json_req, headers=header) print json.dumps(json.loads(response.text), indent=3) #ce ---------------------------------------------------------------------------- #include <WinHttp.au3> Opt("MustDeclareVars", 1) Opt("TrayIconDebug", 1) Global $sAddress = 'https://api.betfair.com/exchange/betting/json-rpc/v1/' Global $sPostData = 'https://api.betfair.com/exchange/betting/json-rpc/v1/listEventTypes/' Global $sAppKey = '4YpsEhdsgtedjd' Global $sSession_key = 'BhKl7Ijdu4E3pzHhKu7K5fQrvzf9p3wq/diRMt7bZka7' Global $sjson_req = '{"filter":{ }}' Global $hOpen = _WinHttpOpen() ; Get Session handle ; ##### CHECKED AND VALID HANDLE IS RETURNED ##### Global $hConnect = _WinHttpConnect($hOpen, $sAddress) ; Get connection handle ; ##### CHECKED AND VALID HANDLE IS RETURNED ##### Global $hRequest = _WinHttpOpenRequest($hConnect, 'POST') ; Make a request ; ##### CHECKED AND VALID HANDLE IS RETURNED ##### ; Add header fields to the request _WinHttpAddRequestHeaders($hRequest, 'X-Application: ' & $sAppKey) _WinHttpAddRequestHeaders($hRequest, 'X-Authentication: ' & $sSession_key) _WinHttpAddRequestHeaders($hRequest, 'Accept: application/json') _WinHttpAddRequestHeaders($hRequest, 'Content-Type: application/json') _WinHttpSendRequest($sPostData, 'Data=' & $sjson_req, $hRequest) ; Send it _WinHttpReceiveResponse($hRequest) ; Wait for the response ; Check if there is a response Global $sHeader, $sReturned If _WinHttpQueryDataAvailable($hRequest) Then $sHeader = _WinHttpQueryHeaders($hRequest) MsgBox(64, 'Header', $sHeader) Do $sReturned &= _WinHttpReadData($hRequest) Until @error ConsoleWrite($sReturned) ; Print returned Else ConsoleWriteError('!No data available.' & @CRLF) MsgBox(48, 'Failure', 'No data available.') ;##### <==== ALWAYS FAILS HERE! ##### EndIf ; Close handles _WinHttpCloseHandle($hRequest) _WinHttpCloseHandle($hConnect) _WinHttpCloseHandle($hOpen) I am sure that I have probably missed out a vital line, but for the life of me I can't see the wood for the trees anymore.
      Anyone got any suggestions?
      Many thanks,
      Pete
    • By gahhon
      I only found that AutoIt can actually execute the entire python script or execute the .exe (converted to .exe from .py)
      But what if I just want call the particular function? If that possible to do so?
      This is because python can't create fancy GUI like AutoIT does. So my plan is use AutoIT to have fancy GUI.
      Then each buttons will trigger specific function in the python script or .exe file.
      For instances:
      btnSum - trigger function in python script or .exe file (funcSum)
      btnMinus - trigger function in python script or .exe file (funcMinus)
       
      Thanks for advance information.
    • By n3wbie
      Hello m trying to learn python 
      m interested in knowing if there is koda like gui designer for python
      please also help me what all additional modules i require
      like ones which are famous
      i have already done with
      1.Scrapy
      2.Openpyxl
      3.twister
      4.selenium
      5.Requests
      6.pdfrw
       
    • By breakbadsp
      I want to run a python script from autoit. 
      I know we can do this with shellexecute or run , but this python script takes 3 cmd line arguments.
      How to pass them from autoit script?
      I tried many ways.
      Following solution also not working 
      e.g. 
      RunWait( 'fullpath\Python.exe Scriptpath\ReadLog.py  -f "file.log" -k "key" -e "errMsg" ') Found solution:
      RunWait( 'fullpath\Python.exe ReadLog.py -f "file.log" -k "key" -e "errMsg" ', 'Working_directory_path')  
      PFB description:
      https://stackoverflow.com/questions/45757834/how-to-pass-command-line-arguments-to-a-python-script-anyscript-while-executin
       
×
×
  • Create New...