Difference between revisions of "Command line parameters and environment variables/es"

From Free Pascal wiki
Jump to navigationJump to search
Line 58: Line 58:
 
  if HasOption('ayuda') then ... </delphi>
 
  if HasOption('ayuda') then ... </delphi>
  
=== Read the parameter value ===
+
=== Leyendo el valor del parámetro ===
  
&nbsp;&nbsp;&nbsp; Each parameter can be given a value. For example:
+
&nbsp;&nbsp;&nbsp; Cada parámetro puede tener un valor. Por ejemplo:
  
   project1 -f filename
+
   proyecto1 -a nombrefichero
  
&nbsp;&nbsp;&nbsp; or with the long form:
+
&nbsp;&nbsp;&nbsp; o en una forma larga:
  
   project1 --file=filename
+
   project1 --archivo=nombrefichero
  
<delphi>  writeln('f=',GetOptionValue('f','file')); </delphi>
+
<delphi>  writeln('archivo = ',GetOptionValue('a','archivo')); </delphi>
  
&nbsp;&nbsp;&nbsp; Note: if you get the error message ''Option at position 1 needs an argument : f.'' then you forgot to add the option in the ''CheckOptions'' call.
+
&nbsp;&nbsp;&nbsp; Nota: Si se obtiene el mensaje de error ''Option at position 1 needs an argument : a.'' es que hemos olvidado añadir la opción en la llamada ''CheckOptions''.
  
 
=== Checking parameters for validity ===
 
=== Checking parameters for validity ===

Revision as of 22:11, 27 January 2009

English (en) español (es) suomi (fi) français (fr) русский (ru)

Parámetros de la línea de órdenes y variables de entorno

Introducción

   Al arrancar un programa el usuario puede poner en la línea de órdenes parámetros y variables de entorno de la configuración. Por ejemplo, el compilador de FreePascal obtiene la mayoría de sus parámetros por medio de las opciones de la línea de orden:

 fpc -Fudirectory -gh unidad1.pas

La esencia de Parámetros de la línea de órdenes

    Un programa Pascal accede a los parámetros por medio de ParamStr y ParamCount. ParamStr(0) contiene la ruta y nombre del programa mismo. ParamStr(1) es el primer parámetro. ParamCount es el número de parámetros.

<delphi> program Project1; {$mode objfpc}{$H+}

var
  i: Integer;
begin
  writeln('Programa: ',ParamStr(0));
  for i:=1 to ParamCount do
    writeln('Parámetro  ',i,': ',ParamStr(i));
end. </delphi>

    Por ejemplo:

 $ /tmp/proyecto1 -a
  Programa: /tmp/proyecto1
  Parámetro 1: -a 

Parámetros de línea de órdenes cómodos

    Un buen programa debe dar un mensaje de ayuda cuando es invocado con los parámetros incorrectos y debe seguir una forma consistente de leer los parámetros. La unidad custapp que viene con FPC proporciona la clase TCustomApplication, que proporciona las funciones que fácilmente comprueba y lee parámetros. Por supuesto se puede tener acceso a los parámetros directamente vía ParamStr y ParamCount.

    Every LCL application uses this automatically. The Application object is a TCustomApplication.

    If you want to write a non LCL program, then create in lazarus a new project of type 'Console Application'. This will create a project1.lpr with some nice goodies, that almost all programs need. Go to the DoRun method.

Comprobando los parámetros

    Con TCustomApplication podemos acceder a los parámetros por su nombre. Por ejemplo el programa puede mostrar un texto de ayuda cuándo el usuario solicita el parámetro de ayuda -?, o --ayuda en su forma larga. Para comprobar cuándo el usuario llama al programa con -? or --ayuda utilizaremos esto:

<delphi> if HasOption('h?','ayuda') then begin

  MuestraAyuda;
  Halt;
end; </delphi>

    Nota: En un formulario de la LCL hay que preceder con Application. a HasOption. Por ejemplo:

<delphi> if Application.HasOption('?','ayuda') then begin

  MuestraAyuda;
  Halt;
end; </delphi>

<delphi> // Sí únicamente queremos admitir la opción corta usaremos:

if HasOption('?',) then ...
// Sí únicamente queremos admitir la opción larga usaremos:
if HasOption('ayuda') then ... </delphi>

Leyendo el valor del parámetro

    Cada parámetro puede tener un valor. Por ejemplo:

 proyecto1 -a nombrefichero

    o en una forma larga:

 project1 --archivo=nombrefichero

<delphi> writeln('archivo = ',GetOptionValue('a','archivo')); </delphi>

    Nota: Si se obtiene el mensaje de error Option at position 1 needs an argument : a. es que hemos olvidado añadir la opción en la llamada CheckOptions.

Checking parameters for validity

    Command line parameters are free text, so the user can easily do typing errors. Checking the syntax of the parameters is therefore mandatory. You can use the CheckOptions method for this:

    You can define, what parameters are allowed, which ones ones need a parameter and in case of a syntax error you can get an error message plus the options that were wrong to print helpful and detailed errors.

    Examples: <delphi> ErrorMsg:=CheckOptions('hf:','help file:');</delphi>

    This allows passing short options -f value and -h. It allows passing long options --help or --file=filename. It does not allow --help with a value, nor --file without a value.