Jefrey

CmdLine UDF (get value/existence/flag)

3 posts in this topic

#1 ·  Posted (edited)

I wrote this very simple functions to parse command line arguments.

It can get:

Simple key/value

Example. The following code:

#include "cmdline.au3"

MsgBox(0, _CmdLine_Get('color'))

Will return "white" if you run the script in one of these ways (quotes are optional but mandatory if you're going to use spaces):

  • script.exe -color "white"
  • script.exe --color white
  • script.exe /color white

Existence

Example. The following code:

#include "cmdline.au3"

If _CmdLine_KeyExists('givemecoffee') Then
   ConsoleWrite('You want coffee.')
Else
   ConsoleWrite('You do not want coffee.')
EndIf

Will return "You want coffee." if you run one of these:

  • script.exe -givemecoffee
  • script.exe --givemecoffee
  • script.exe /givemecoffee

And the following code:

#include "cmdline.au3"

If _CmdLine_ValueExists('givemecoffee') Then
   ConsoleWrite('You want coffee.')
Else
   ConsoleWrite('You do not want coffee.')
EndIf

Will return "You want coffee." if you run one of these:

  • script.exe givemecoffee
  • script.exe "givemecoffee"

Flags

Example. This script:

#include "cmdline.au3"

ConsoleWrite("You want: ")

If _CmdLine_FlagEnabled('C') Then
  ConsoleWrite("coffee ")
EndIf

If _CmdLine_FlagEnabled('B') Then
   ConsoleWrite("beer ")
EndIf

ConsoleWrite(" and you do not want: ")

If _CmdLine_FlagDisabled('V') Then
  ConsoleWrite("vodka ")
EndIf

If _CmdLine_FlagDisabled('W') Then
   ConsoleWrite("wine ")
EndIf

ConsoleWrite(" but you did not tell me if you want: ")

If Not _CmdLine_FlagExists('S') Then
   ConsoleWrite("soda ")
EndIf

If Not _CmdLine_FlagExists('J') Then
   ConsoleWrite("juice ")
EndIf

Will return "You want: coffee beer  and you do not want: vodka wine  but you did not tell me if you want: soda juice" if you run:

  • script.exe +CB -VW

Getting argument by its index

You can also read the $CmdLine (1-based index) through this function. The advantage is that if the index does not exist (the user did not specify the argument), it won't break your script. It will just return the value you specify in the second function parameter.

#include "cmdline.au3"

$first_argument = _CmdLine_GetValByIndex(1, False)

If Not $first_argument Then
   ConsoleWrite("You did not specify any argument.")
Else
   ConsoleWrite("First argument is: " & $first_argument)
EndIf

Just a note: The second value of _CmdLine_GetValByIndex function can be an integer value, a string, a boolean value, an array or anything you want it to return if the index does not exist in $CmdLine array.

This parameter is also available in _CmdLine_Get() function, also as a second function parameter. In this case, it will return this value if the key was not found. Example:

#include "cmdline.au3"

$user_wants = _CmdLine_Get("iwant", "nothing")

ConsoleWrite("You want " & $user_wants)

So, if you run:

  • script.exe /iwant water

It will return "You want water". But if you run just:

  • script.exe

It will return "You want nothing". Please note that, as these two are the only functions in this library meant to return strings, the second parameter is not available for the other functions. By default, if you do not specify any fallback value, it returns null if the wanted value could not be found.

Also, please note that this UDF can NOT parse arguments in the format (key=value). Example:

  • script.exe key=value IT WILL NOT WORK

 

Here is the code:

#include-once

#comments-start
   CmdLine small UDF
   coder: Jefrey (jefrey[at]jefrey.ml)
#comments-end

Func _CmdLine_Get($sKey, $mDefault = Null)
   For $i = 1 To $CmdLine[0]
      If $CmdLine[$i] = "/" & $sKey OR $CmdLine[$i] = "-" & $sKey OR $CmdLine[$i] = "--" & $sKey Then
         If $CmdLine[0] >= $i+1 Then
            Return $CmdLine[$i+1]
         EndIf
      EndIf
   Next
   Return $mDefault
EndFunc

Func _CmdLine_KeyExists($sKey)
   For $i = 1 To $CmdLine[0]
      If $CmdLine[$i] = "/" & $sKey OR $CmdLine[$i] = "-" & $sKey OR $CmdLine[$i] = "--" & $sKey Then
         Return True
      EndIf
   Next
   Return False
EndFunc

Func _CmdLine_ValueExists($sValue)
   For $i = 1 To $CmdLine[0]
      If $CmdLine[$i] = $sValue Then
         Return True
      EndIf
   Next
   Return False
EndFunc

Func _CmdLine_FlagEnabled($sKey)
   For $i = 1 To $CmdLine[0]
      If StringRegExp($CmdLine[$i], "\+([a-zA-Z]*)" & $sKey & "([a-zA-Z]*)") Then
         Return True
      EndIf
   Next
   Return False
EndFunc

Func _CmdLine_FlagDisabled($sKey)
   For $i = 1 To $CmdLine[0]
      If StringRegExp($CmdLine[$i], "\-([a-zA-Z]*)" & $sKey & "([a-zA-Z]*)") Then
         Return True
      EndIf
   Next
   Return False
EndFunc

Func _CmdLine_FlagExists($sKey)
   For $i = 1 To $CmdLine[0]
      If StringRegExp($CmdLine[$i], "(\+|\-)([a-zA-Z]*)" & $sKey & "([a-zA-Z]*)") Then
         Return True
      EndIf
   Next
   Return False
EndFunc

Func _CmdLine_GetValByIndex($iIndex, $mDefault = Null)
   If $CmdLine[0] >= $iIndex Then
      Return $CmdLine[$iIndex]
   Else
      Return $mDefault
   EndIf
EndFunc
Edited by Jefrey
4 people like this

My stuff

Spoiler

My UDFs  _AuThread multithreading emulation for AutoIt · _ExtInputBox an inputbox with multiple inputs and more features · forceUTF8 fix strings encoding without knowing its original charset · JSONgen JSON generator · _TCPServer UDF multi-client and multi-task (run on background) event-based TCP server easy to do · _TCPClient_UDF multi-server and multi-task (runs on background) event-based TCP client easy to do · ParseURL and ParseStr functions ported from PHP · _CmdLine UDF easily parse command line parameters, keys or flags · AutoPHP Create documents (bills, incomes) from HTML by sending variables/arrays from AutoIt to PHP · (Un)Serialize Convert arrays and data into a storable string (PHP compatible) · RTTL Plays and exports to MP3 Nokia-format monophonic ringtones (for very old cellphones) · I18n library Simple and easy to use localization library · Scripting.Dictionary OOP and OOP-like approach · Buffer/stack limit arrays to N items by removing the last one once the limit is reached · NGBioAPI UDF to work with Nitgen fingerprint readers · Serial/Licensing system require license key based on unique machine ID from your users · HTTP a simple WinHTTP library that allows GET, POST and file uploads · Thread true AutoIt threads (under-dev) Classes _WKHtmlToX uses wkhtmlto* to convert HTML files and webpages into PDF or images (jpg, bmp, gif, png...) Snippets _Word_DocFindReplaceByLongText replace strings using Word UDF with strings longer than 255 characters (MSWord limit) rangeparser parser for printing-like pages interval (e.g.: "1,2,3-5") EnvParser parse strings/paths with environment variables and get full path Random stuff Super Mario beep sound your ears will hurt

 

Share this post


Link to post
Share on other sites



#2 ·  Posted (edited)

Thanks for sharing
Very useful UDF.

mLipok

 

btw:
added here , and please fix your signature.

 

Edit:

Can you make a zip with your UDF and post it to this thread or As described herein or here

Edited by mLipok

Signature beginning:   Wondering who uses AutoIT and what it can be used for ?
* GHAPI UDF - modest begining - comunication with GitHub REST API *
ADO.au3 UDF     POP3.au3 UDF     XML.au3 UDF    How to use IE.au3  UDF with  AutoIt v3.3.14.x  for other useful stuff click the following button

Spoiler

Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind. 

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft.au3 UDF * TeamViewer.au3 UDF * JavaManagement UDF * VIES over SOAP * WinSCP UDF * GHAPI UDF - modest begining - comunication with GitHub REST API *

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 - BETA * ADO.au3 UDF SMTP Mailer UDF *

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Best coding practices * 

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities * _IEquerySelectorAll() (by uncommon) * 

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, "The Art of Computer Programming"
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

Signature last update: 2017-06-04

Share this post


Link to post
Share on other sites

#3 ·  Posted (edited)

Dear Jefrey,

Many Thanks,

Let me share a version of some of your examples trying to get StdOut from ConsoleWrite in Uncompiled scripts

save this as 01_child.au3

#include "cmdline.au3"

Local $Output = _CmdLine_Get('color')
MsgBox(0, "", $Output)
ConsoleWrite($Output)

save this as 01_main.au3

#include <Constants.au3>

#cs ----------------------------------------------------------------------------
Will return "white" if you run the script in one of these ways
(quotes are optional but mandatory if you're going to use spaces)
#ce ----------------------------------------------------------------------------
Local $sFilePath = '"' & @ScriptDir & '\01_child.au3"'
RunWait(@AutoItExe & " " & $sFilePath & ' -color "white"')

RunWait(@AutoItExe & " 01_child.au3" & ' -color white')

RunWait(@AutoItExe & " 01_child.au3" & ' --color white')
RunWait(@AutoItExe & " 01_child.au3" & ' /color white')

$iPID = Run(@AutoItExe & " /AutoIt3ExecuteScript " & "01_child.au3" & ' /color "white cafe"', "", @SW_HIDE, $STDERR_CHILD + $STDOUT_CHILD)
ProcessWaitClose($iPID)
Local $sOutput = ""
$sOutput = StdoutRead($iPID)
MsgBox(0, "Stdout Read", "Stdout Read: " & @CRLF & $sOutput)
ConsoleWrite($sOutput & @CRLF)

 

And this could be for example 04:

create 04_child.au3 in the same way as explained above

and save below code as 04_main.au3

#include <Constants.au3>

#cs ----------------------------------------------------------------------------
Flags
Will return "You want: coffee beer  and you do not want: vodka wine  but you did not tell me if you want: soda juice" if you run:
    script.exe +CB -VW
#ce ----------------------------------------------------------------------------

;Local $sFilePath = '"' & @ScriptDir & '\04_child.au3"'
;Local $iPID = Run(@AutoItExe & " /AutoIt3ExecuteScript " & $sFilePath & ' +CB -VW', "", @SW_HIDE, $STDERR_CHILD + $STDOUT_CHILD)
Local $iPID = Run(@AutoItExe & " /AutoIt3ExecuteScript " & "04_child.au3" & ' +CB -VW', "", @SW_HIDE, $STDERR_CHILD + $STDOUT_CHILD)

;This would be if compiled:
;Local $iPID = Run(@ComSpec & " /C 04_child.exe +CB -VW", @ScriptDir, @SW_HIDE, $STDERR_CHILD + $STDOUT_CHILD)

ProcessWaitClose($iPID)
Local $sOutput = ""
$sOutput = StdoutRead($iPID)
MsgBox(0, "Stdout Read", "Stdout Read: " & @CRLF & $sOutput)
ConsoleWrite($sOutput & @CRLF)

 

Edited by robertocm

Share this post


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

  • Similar Content

    • mihaijulien
      By mihaijulien
      Hello,
      I compiled a script I made that takes a command line parameter (the version of a .msi installer) when launched. The script was compiled with the /console option. The script (.au3) works fine but the executable returns  the following error:  
      Error: array variable has incorrect number of subscripts or subscript dimension range exceeded  
    • zetaimmersion
      By zetaimmersion
      Hi all. 
      I am trying to do 2 things but i cannot seem to get any traction on how to read/implement this idea.
      Premise: PowerPoint file in C\temp\presentation.pptx that contains on the first slide 2 entries as "<one>" and "<two>" which need to be replaced with "user1" and "user2", then a silent Outlook send mail containing the file with a predefined body and subject.
      I narrowed it down to COM objects as the Office does not like intrusive open AutoIt functions. I installed OLE/COM Object Viewer to understand how to create the commands but i am still stuck. So far i am trying to user water's code but i suck
      COM object i was originally trying to modify
      Dim $oPPT, $oPres $oPPT = ObjCreate("PowerPoint.Application") $oPPT.Visible = True $oPres = $oPPT.Presentations.Read Water's code below (0.1% modified)
      #include <File.au3> #include "PowerPoint.au3" #include <misc.au3> Global $sFile = "C:\temp\presentation.pptx" Global $sString2Search = "<username>", $sString2Replace = "Password", $iReplaceOnce = 1, $sFullLogFile = "C:\temp\pptxlog.txt" _ProcessPpt($sFile) Func _ProcessPpt($sFile) $oApp = _PPT_PowerPointApp() Local $bChange = False Local $oInterface = $oApp.Presentations Local $oPresentation = $oInterface.Open($sFile, False, False, False) If @error Then _FileWriteLog($sFullLogFile, "E Error " & @error & " opening File " & $sFile) Return SetError(1, 0, 0) EndIf ;it does not even open my file and from here not sure how to read the text and replace it EndFunc ;==>_ProcessPpt  
    • Simpel
      By Simpel
      Hi.
      Local $sPDFtk = FileGetShortName(@ScriptDir & "\pdftk.exe") Local $sInputPDF = FileGetShortName(@ScriptDir & "\Prodis_Test.pdf") Local $sSig_1 = FileGetShortName(@ScriptDir & "\Sig_1.pdf") Local $sTempPDF = FileGetShortName(@ScriptDir & "\Prodis_Test_TEMP.pdf") $iSuccess = ShellExecuteWait($sPDFtk, $sInputPDF & " stamp " & $sSig_1 & " output " & $sTempPDF, "", "", @SW_HIDE) @ScriptDir is "H:\_Conrad lokal\Downloads\AutoIt3\_COX". As you can see there is a space in the path.
      I know that ShellExecuteWait is working with FileGetShortName at the filename. It seems to me that I can't pass the parameters that way. But without FileGetShortName it's not working too.
      Ideas? Regards, Conrad
    • YellowLab
      By YellowLab
      I am having a very unique, but repeatable problem with ImageMagick COM interface. Here are the applicable lines of code:
      $oIM=ObjCreate("ImageMagickObject.MagickImage.1")
      and then later on...
      $oIM.Convert(String($arFileList[$nFileIndex])&'[0]',"-alpha", "remove",@TempDir&"\temp.jpg")
      the array points to a pdf file with the "convert" command converting the first page of the pdf to a jpg with any alpha layer removed.
      Every time, without fail, the first time I run the script on a freshly booted machine it crashes on the $oIM.Convert command. It does this if it isn't compiled and says there is an error executing the command on the object. If compiled, i get an error that autoit has stopped responding. Anytime I run the script, compiled or not, after this initial crash everything works perfectly fine.
      I am totally at a loss as to why this is occurring and how to correct it.
    • Javik
      By Javik
      Is there a way to read data directly from the Windows Component Object Model (COM) interface?
      I am trying to make a really simple disk space reporter tool for accounts on an Active Directory domain, to read the disk quota limit for the logged on user's home directory, and report how much disk space they are currently using.
      ,
      MSDN:  IDiskQuotaUser interface
      https://msdn.microsoft.com/en-us/library/windows/desktop/aa365033(v=vs.85).aspx
      GetQuotaLimit
      GetQuotaUsed