Difference between revisions of "Console Mode Pascal/es"

From Lazarus wiki
Jump to navigationJump to search
()
()
Line 3: Line 3:
 
== Programación con Pascal en modo consola ==
 
== Programación con Pascal en modo consola ==
 
por [[User:Kirkpatc]]
 
por [[User:Kirkpatc]]
=== ===
+
=== Empezando ===
 
   Muchos de nosotros escribíamos programas en Pascal mucho antes de que los interfaces gráficos de usuario (GUIs) y los entornos de desarrollo integrados (IDEs) se pusieran de moda. Muchos otros son principiantes en programación en Pascal y necesitan poder probar las herramientas básicas del lenguaje. Otros necesitan escribir aplicaciones de consola o en modo de texto para realizar tareas complejas de control del sistema.
 
   Muchos de nosotros escribíamos programas en Pascal mucho antes de que los interfaces gráficos de usuario (GUIs) y los entornos de desarrollo integrados (IDEs) se pusieran de moda. Muchos otros son principiantes en programación en Pascal y necesitan poder probar las herramientas básicas del lenguaje. Otros necesitan escribir aplicaciones de consola o en modo de texto para realizar tareas complejas de control del sistema.
  

Revision as of 19:19, 27 January 2009

Deutsch (de) English (en) español (es) suomi (fi) magyar (hu) 日本語 (ja) русский (ru) slovenčina (sk)

Programación con Pascal en modo consola

por User:Kirkpatc

Empezando

   Muchos de nosotros escribíamos programas en Pascal mucho antes de que los interfaces gráficos de usuario (GUIs) y los entornos de desarrollo integrados (IDEs) se pusieran de moda. Muchos otros son principiantes en programación en Pascal y necesitan poder probar las herramientas básicas del lenguaje. Otros necesitan escribir aplicaciones de consola o en modo de texto para realizar tareas complejas de control del sistema.

   Lazarus dispone de un entorno ideal para aprender Pascal, y para desarrollar programas en modo texto. Todas las funcionalidades del IDE se pueden utilizar, incluyendo el editor de código con su resaltado de sintaxis, acceso a las librerías, búsquedas complejas y herramientas de completado de código y comprobación de sintaxis. Si no se quiere un formulario con componentes visuales no es necesario tenerlo, pero el editor de Lazarus es un gran entorno para desarrollar programas. Puedes compilar y ejecutar programas durante el desarrollo, sin abandonar el Editor.

   Para dar inicio a un programa en modo consola, hay que ir al Menú principal y en la opción Proyecto seleccionar Nuevo Proyecto ... y en la ventana que aparece seleccionar Programa, Aplicación de consola o Programa personalizado. El IDE no generará todos los ficheros que están asociados con una aplicación gráfica completa y no abrirá la ventana del Inspector de objetos y si abrirá el Editor de código con el esqueleto del programa, esperando que introduzcamos nuestro código.

Custom Program

A very minimalistic pascal program. Choose this if you want to do everything yourself or just do some quick tests and delete the files soon.

Program

Same as Custom Program, but the IDE helps you a bit more. For example when you add another unit the IDE will automatically add the unitname to the program uses section. This behavior is defined in the project options. So you can go between 'Program' and 'Custom Program' at any time.

An example for complete beginners:

program Project1;
{$mode objfpc}{$H+}
uses
  {$IFDEF UNIX}{$IFDEF UseCThreads}
  cthreads,
  {$ENDIF}{$ENDIF}
  Classes
  { you can add units after this };
begin
  writeln('Hello World!');
  readln;
end.

Console Application

This creates a program with a new class derived from TCustomApplication. TCustomApplication provides a lot of the common things and makes programming command line utilities easy. For example checking command line options, writing help, checking environment variables and exception handling. All LCL programs use this automatically.

Compile

When you have finished your program (or program fragment) you can compile and run it by selecting Run -> Run from the Main Menu or clicking on the Green (Run) triangle symbol in the Button Bar. Any compiler messages (warnings, progress reports or error messages) will appear in the Message Box, and hopefully there will eventually be a message to say

'Project "Project1" successfully built.:)'.

Run

But where is the program??!!

If you have not yet saved the program, then the IDE put it into the temporary directory (e.g. /tmp under linux, C:\temp under windows, see Environment Options / Files / Directory for building test projects).

If you already saved the project, then the program was created in the same directory, where you saved the project1.lpi file.

You can execute the program by going to a console (terminal) window, use cd to change to the directory and typing the name of the program (in Unix/Linux, if it is in the current directory you will probably have to type

./Project1

as it won't be found in the standard PATH). However, it can be very inconvenient to keep skipping out of the Lazarus Editor and into a terminal window and back again. Fortunately, there is a mechanism that allows a terminal window to be opened from within the Lazarus environment.

Run in IDE

From the Main Menu, select Run -> Run Parameters, then check the box for "Use launching application". The first time you do this and try the Compile/Run sequence, you will probably get a rude message to say

"xterm: Can't execvp /usr/share/lazarus//tools/runwait.sh: Permission denied".  

If this happens, you need to change the permissions on the appropriate file (for example using chmod +x filename, or using the Windows utility for changing permissions); you might have to do this as root. After this, each time you launch your program, a console box will appear and all your text i/o (readln, writeln etc) will appear in it.

After your program has finished execution, a message "Press enter" appears on the screen. Thus any output your program generated will remain on the screen until you have had a chance to read it; after you press 'enter' the console window closes.

Examples

You can use the Lazarus editor to try out all the examples in the standard Pascal text-books, or you can write your own. Some of the most useful procedures are those for executing system commands or for running other programs (which may have been written in Pascal, C or Perl, or may be shell or Batch scripts).

Execute shell command

Here is an example for a Custom Program or Program:

Program TryShell;
uses classes, unix;
var S: longint;
begin
  S := fpsystem ('/bin/ls -la *.p*'); //lists .pp, .pas, .php, .png etc in current directory
  writeln ('Program exited with status : ', S)
end.

Example: update fpc and lazarus

Rather more complex commands can be executed. For example, if you have already checked out the SVN repositories for FPC and Lazarus (see fpc buildfaq) you could keep your FPC and Lazarus source files up-to-date by retrieval from the SVN repository with the following sequence of calls:

Program LazUpdate;
uses classes, unix;
var s : longint;
begin 
  S := fpsystem ('cd /usr/local/src/fpc/devel/fpc ; make clean');
  S := fpsystem ('cd /usr/local/src/fpc/devel/lazarus ; make clean');
  S := fpsystem ('cd /usr/local/src/fpc/devel ; svn update fpc >& ~/cvscheckout.log');
  S := fpsystem ('cd /usr/local/src/fpc/devel ; svn update lazarus >& ~/cvslaz.log');
end.

Note that issuing the command

fpsystem ('cd /somedirectory')

followed by

fpsystem ('do something in that subdirectory')

doesn't work, because after each fpsystem function call the execution of the program returns to the directory it started in; so we need to include multiple statements per line within our calls to shell.

Of course, you don't have to enter every command as a separate line of Pascal; you could create a script file like this (from fpc buildfaq):

#!/bin/sh
cd /usr/local/src/fpc/devel
cd fpc
make clean
cd ..
cd lazarus
make clean
cd ..
svn up fpc >& ~/cvscheckout.log
svn up lazarus >& ~/cvslaz.log 

Name it updatelaz.sh, and then call it from a Pascal program thus:

Program LazUpdate1;
uses classes, unix;
var S : longint; 
begin
  S := fpsystem ('updatelaz.sh')
end.

Command line parameters

See Command line parameters and environment variables.

Orginal contributors

Esta página se ha convertido desde la versión epikwiki. Original de User:Kirkpatc. Traducción de User:Iskraelectrica. Enero de 2009.


Ejecutando programas externos