ALL Scripting Languages Refrence Guide

Embed Size (px)

Citation preview

Introduction to ScriptingAE 6382

AE6382

What is a scripting

Scripting is the process of programming using a scripting language A scripting language, like C, Fortran, and Java, has expressions, conditional statements, and loop statements. Unlike C, Fortran, and Java a scripting language has

Loose typing Interpreted rather than compiled Usually as some higher level abstractions or built-in functionality

AE6382

Scripting Features

Scripting languages are generally interpreted rather than compiled This results in slower execution times compared to a compiled language

C and Fortran are generally fastest Java is compiled to bytecode that runs on a virtual machine and is slower The implementation of each individual interpreter varies greatly

Perl, Python, and Ruby are compiled at runtime into an internal format that increases performance Shell scripts and MATLAB re-evaluate each statement every time

Development cycle is shortened edit/run

AE6382

Scripting Features

Scripting languages do not, in general, use strong typing of variables

A variable may during the course of execution contain strings, integers, and objects

Scripting languages frequently build into the basic language higher order abstractions

Text processing Regular expressions System interface mechanisms

Most scripting interpreters can be embeddedt into other programs to provide scripting capability within that program

Microsoft Office uses Visual Basic for ApplicationsAE6382

Scripting Languages

Simple command/shell scripting, level 1, is the simplest form of scripting Intended to provide a batch execution capability Unix/Linux

bash, ksh (Korn shell), sh (Bourne shell) csh (C shell), tsch These shells can work interactively or in script mode Have basic programming constructs (if, loops, ) cmd/command have no programming constructs Windows PowerShell (4Q2006) will have extensive scripting based on C# language

Windows

AE6382

Scripting Languages

Limited scripting languages, level 2, have more sophisticated language structure but are limited in their native functionality

No native file I/O capability for example Available on Unix/Linux and Windows C based syntax Used almost exclusively as the client-side scripting language in the various web browsers Can be used as a system scripting language in Windows via the Windows Scripting Host Not generally used in Unix/Linux for general purpose scripting

JavaScript / Jscript / ECMAScript

SpiderMonkey is C based JS interpreter Rhino is Java based JS interpreterAE6382

Scripting Languages

VBScript

Available only on Windows, based on Visual Basic for Applications (VBA) Can be used as the client-side scripting language in Internet Explorer Most often used with Windows Active Server Pages (ASP) for IIS based web sites Can be used as a system scripting language in Windows via the Windows Scripting Host

AE6382

Scripting Languages

Full scripting languages, level 3, have a sophisticated language structure and extensive application support Perl Practical Extraction and Reporting Language

A procedure based language with support for objects Extensive text processing capabilities and regular expressions Extensible using modules C based syntax with plethora of symbols Developed in late 1980s An object oriented language with some procedure traits Extensible A format based syntax Developed in early 1990sAE6382

Python (also Jython)

Scripting Languages

Ruby

An object oriented language Extensible C like syntax with minimal symbols (no {} () ) Developed in early 1990s A procedural language Extensible A stack evaluation syntax, similar to Lisp (lots of []) Developed as an embeddable scripting language Developed in late 1980s

TCL Tool Command Language

AE6382

Scripting Languages

Other niche scripting languages

BeanShell

Makes it possible to use Java as a scripting language C-like, objects, cross-platform, has a Java version

REXX

AE6382

Perl

General purpose scripting language Practical Extraction and Reporting Language Based on the Unix program awk in its early incarnation Runs everywhere

On Unix/Linux it runs standalone using #! script file convention On Windows it can run standalone or as an ActiveX scripting engine Extensive text processing capabilities including built-in regular expressions Can be easily extended, there is extensive support for all types of system programming Has syntax to support object based programming Most Unix system calls are built-in functions The built-in system calls will do the right thing in WindowsAE6382

Pros

Perl

Cons

Can be difficult for beginners to learn Variable naming scheme is initially confusing There is a high learning curve

AE6382

Perl

Has 3 classes of variables

$var @var %var

-

scalar (integer, real, string, ...) array of scalars, $var[0] hash of scalars, $var{key}

Has local, lexical, and global scoping of variables Namespace separation Objects and references are supported Has the same set of operators as C plus some Lexical and global scoping of variables Statements end with ; Comments are everything after # on a line Functions sub name { ... }AE6382

Perl

Has the same set of operators as C plus some additional Statements end with ; (semi-colon) Comments are everything after # on a line The usual complement of conditional statements

if then else (also unless then else) for for each while sub name () { }

The usual loop statements

Functions and methods are defined similarly

AE6382

Perl

Loop statementsfor ($i=0 ; $i < 10 ; $i++) { printf i=%4d\n,$i; } while () { print; } @list = (0,5,8,12); foreach $value (@list) { print Value=$value\n; } %hash = (part1=>0,part3=>70,part2=>4); foreach $key (sort keys %hash) { print Value=$hash{$key}\n; } foreach $value (0,5,8,12) { print Value=$value\n; }

AE6382

Perl

Logical statementsif ($i == 1) { print i=$i\n; $i++; } unless ($i == 1) { print Error: i != 1\n; $i++; }

die Unable to open file if !open(IN,filename); if ($i == 1) { print Group 1\n; } else { print Unknown group\n; } if ($i == 1) { print Group 1\n; } elsif ($i == 2) { print Group 2\n; } elsif ($i == 3) { print Group 3\n; } else { print Unknown group\n; }

AE6382

Perl

Native Regular Expression Support

while () { next if m/.*error.*/; print; } foreach $line (@lines) { next if $line =~ m/^#/; @values = ($line =~ m/.+a=([0-9]+).+c=([0-9]+)/); print $values[0] $values[1]\n; }

@lines contains (an array of strings): # a b c a=10 b=23 c=16 a=12 b=43 c=17 a=63, b=2, c=999

AE6382

Perl

Support for objects

use Modulename; $var = Modulename::new(); $var->method(...); $var->{property};

(include class definition) (instantiate object) (invoke method) (access property)

Does not have a class keyword, a class is defined as a Perl module where the functions are invoked as methods and the use of the bless keyword.

AE6382

M/S Scripting Documentation

Script56.chm is the Windows scripting documentation file Local copy http://www.ae.gatech.edu/classes/ae6 382/MS_scripting/

AE6382

JavaScript / JScript

General purpose scripting language Usually appears only in web browsers Available on most platforms

In Windows Jscript is available as an ActiveX scripting engine, when run under the Windows Scripting Host it can functions as a general scripting system Its syntax is very much like C It has support for objects Limited availability Has limited access to host system (security feature)

Pros

Cons

AE6382

JavaScript / JScript

Variables

Typeless, refer to primitive types and objects Can be arrays Declared with var statement

Uses the usual set of C operators with some additions Statements are terminated with ; Comments marked with // and /* ... */ Functions and methods are declared with function name (...) { ... }

AE6382

JavaScript / JScript

Loop statementsvar stdout = WScript.StdOut; var i; for (i=0 ; i < 10 ; i++) { stdout.WriteLine(i=+i); } var stdout = WScript.StdOut; var stdin = WScript.StdIn; while (! stdin.AtEndOfStream) { line = stdin.ReadLine() stdout.WriteLine(line); } var stdout = WScript.StdOut; var array = new Array(3); array[0] = 2; array[1] = 12; array[2] = 70; for (var value in array) { stdout.WriteLine("Value: "+array[value]); }

AE6382

JavaScript / JScript

Logical statements

if (i == 5) { stdout.WriteLine(Equality failed); } if (i == 1) { stdout.WriteLine(Group 1); } else { stdout.WriteLine(Unknown group); } if (i == 1) { stdout.WriteLine(Group 1); } else if (i == 2) { stdout.WriteLine(Group 2); } else if (i == 3) { stdout.WriteLine(Group 3); } else { stdout.WriteLine(Unknown group); }

AE6382

JavaScript / JScript

Regular Expression Supportvar stdout = WScript.StdOut; var stdin = WScript.StdIn; var re = new RegExp(".*error.*","i"); while (! stdin.AtEndOfStream) { var line = stdin.ReadLine(); if (line.match(re)) { stdout.WriteLine(line); } }

AE6382

JavaScript / JScript

Regular Expression Supportvar stdout = WScript.StdOut; var stdin = WScript.StdIn; var re1 = new RegExp("^#","i"); var re2 = new RegExp(".+a=([0-9]+).+c=([0-9]+)"); var lines = new Array(4); lines[0] = "# a b c"; lines[1] = " a=10 b=23 c=16"; lines[2] = " a=12 b=43 c=17"; lines[3] = " a=63, b=2, c=999"; for (var line in lines) { stdout.WriteLine(lines[line]); if (lines[line].match(re1)) continue; re2.exec(lines[line]); var avalue = RegExp.$1; var cvalue = RegExp.$2; stdout.WriteLine(avalue+", "+cvalue); }

// lines contains (an array of strings): // # a b c // a=10 b=23 c=16 // a=12 b=43 c=17 // a=63, b=2, c=999

AE6382

JavaScript / JScript

Object support

var obj = new Object(); obj.method(...); obj.property; obj[property];

(instantiate object) (invoke method) (access property) (access property)

AE6382

M/S Scripting Documentation

Script56.chm is the Windows scripting documentation file Local copy http://www.ae.gatech.edu/classes/ae6 382/MS_scripting/

AE6382

VBScript

General purpose scripting language Only available on Windows

Available as an ActiveX scripting engine, when run under the Windows Scripting Host it has general usage Can be used as the client-side scripting in IE Simple syntax (Basic) Has support for objects Windows only

Pros

Cons

AE6382

VBScript

Variables

Typeless, refer to primitive types and objects Can be arrays Declared with Dim statement

Uses a small subset of C operators Statements are terminated by the end of line Comments marked with (single quote character) Subroutines Sub name

AE6382

VBScript

Loop statementsDim i i = 0 For i=0 To 9 Step 1 WScript.StdOut.WriteLine "i=" & i Next Do While Not WScript.StdIn.AtEndOfStream Dim line line = WScript.StdIn.ReadLine() WScript.StdOut.WriteLine(line) Loop Dim d Set d d.Add d.Add d.Add 'Create a variable = CreateObject("Scripting.Dictionary") "0", "Athens" 'Add some keys and items "1", "Belgrade" "2", "Cairo" Do Until WScript.StdIn.AtEndOfStream Dim line line = WScript.StdIn.ReadLine() WScript.StdOut.WriteLine(line) Loop

For Each I in d Document.frmForm.Elements(I).Value = D.Item(I) Next

AE6382

VBScript

Logical statements

If i = 5 Then WScript.StdOut.WriteLine Value is & i End If If i = 1 Then WScript.StdOut.WriteLineGroup 1 Else WScript.StdOut.WriteLine Unknown group End If If i = 1 Then WScript.StdOut.WriteLine ElseIf i = 2 Then WScript.StdOut.WriteLine ElseIf i = 3 Then WScript.StdOut.WriteLine Else WScript.StdOut.WriteLine End If

Group 1 Group 2 Group 3 Unknown group

AE6382

VBScript

Regular Expression Support

Dim re Set re = New RegExp re.Pattern = ".*error.*" re.IgnoreCase = True Do While Not WScript.StdIn.AtEndOfStream Dim line line = WScript.StdIn.Readline If re.Test(line) Then WScript.StdOut.WriteLine line End If Loop

AE6382

VBScript

Regular Expression SupportDim line Dim i Dim match Dim re1, re2, matches, submatches Dim lines(4) lines(0) = "# a b c" lines(1) = " a=10 b=23 c=16" lines(2) = " a=12 b=43 c=17" lines(3) = " a=63, b=2, c=999" set re1 = New RegExp set re2 = New RegExp re1.Pattern = "^#" re2.Pattern = ".+a=([0-9]+).+c=([0-9]+)" For i=0 To 3 line = lines(i) WScript.StdOut.WriteLine "--> " & line If Not re1.Test(line) Then ' WScript.StdOut.WriteLine line Set matches = re2.Execute(line) Set match = matches(0) WScript.StdOut.WriteLine match.SubMatches(0) & ", " & match.SubMatches(1) End If Next ' lines contains (an array of strings): ' # a b c ' a=10 b=23 c=16 ' a=12 b=43 c=17 ' a=63, b=2, c=999

AE6382

VBScript

Object support

Set obj = New Object obj.method(...) obj.property

(instantiate object) (invoke method) (access property)

AE6382

Tcl

General purpose scripting language Available on most platforms

In Windows it can run standalone an is also available as an ActiveX scripting engine Interpreter has a small footprint Easily embedded Extensible using C Strange syntax

Pros

Cons

AE6382

Tcl

Variables

Strings are the basic type Can create lists and arrays

Uses the expr command to evaluate expressions Format cmd op op ... op set var value (set counter 5) Reference value: $counter (set i $counter) Use [ ... ] to evaluate immediately

AE6382

Tcl

Loop statementsfor (set i 0} {$i < 10} {incr i 3} { lappend aList $i } set aList set i 1 while {$i cscript sample1.js

// Get the stdin and stdout descriptors // The WScript object is created automatically by WSH var stdin = WScript.StdIn; // properties var stdout = WScript.StdOut; // Get the value to pass to program stdout.WriteLine("Enter value for i: "); var i = stdin.ReadLine(); stdout.WriteLine("Enter value for j: "); var j = stdin.ReadLine(); // Create an instance of the WshShell object (COM object) var WshShell = new ActiveXObject("WScript.Shell"); // Run with access to programs I/O var WshScriptExec = WshShell.Exec("program1"); // Write to the running programs stdio WshScriptExec.StdIn.WriteLine(" "+i+" "+j); // Wait for the running program to exit while (WshScriptExec.Status != 1) { ; } // Read from the running programs stdout var output = WshScriptExec.StdOut.ReadLine(); stdout.WriteLine("Output from program: "+output);

AE6382

Scripting in Windows

sample1.wsf

execute from cmd prompt> sample1.wsf

// Get the stdin and stdout descriptors // The WScript object is created automatically by WSH var stdin = WScript.StdIo; // properties var stdout = WScript.StdOut; // Get the value to pass to program stdout.WriteLine("Enter value for i: "); var i = stdin.ReadLine(); stdout.WriteLine("Enter value for j: "); var j = stdin.ReadLine(); // Create an instance of the WshShell object (COM object) var WshShell = new ActiveXObject("WScript.Shell"); // Run with access to programs I/O var WshScriptExec = WshShell.Exec("program1"); // Write to the running programs stdio WshScriptExec.StdIn.WriteLine(" "+i+" "+j); // Wait for the running program to exit while (WshScriptExec.Status != 1) { ; } // Read from the running programs stdout var output = WshScriptExec.StdOut.ReadLine(); stdout.WriteLine("Output from program: "+output);

AE6382

Windows Scripting Host

WSH is the context within which VBScript and JScript run PerlScript and PythonScript are also available Start WSH scripts using cscript or wscript

cscript - console mode wscript - windows mode, no stdin, stdout, or stderr

The WSF format can contain several scripts in one text file

AE6382

Component Object Model COM

Why use COM The Component Object Model (COM) is the key to making full use of Windows COM is accessible from C++ and scripting Scripting an application is called automation Also referred to as ActiveX and OLE

AE6382

Objects in COM

A class defines an object

Properties are variables Methods are functions Each object has its own copy of the properties When a method is invoked it operates on only the object that is the target of the invocation

When a class is instantiated an object is created

AE6382

Objects in COM

An application can make many classes available for use via COM The client code (a script for example) must create an instance of the class (an object) and save a reference in a variable The applications methods may then be invoked on that object to access the application Using Windows Script Components (see Script56.CHM) scripts can be made available to other COM clients via COM

AE6382

Objects in COM

Two methods for accessing COM

vtables C/C++ Dispatch scripts

Classes contain properties and methods Collections are classes that enumerate objects

Dim worksheets, worksheet, excel ... Set worksheet = excel.Worksheets(sheet1) ... Set worksheet = excel.Worksheets(2) ... excel is an instance of Excel.Application worksheet is an instance of Worksheet class implied Item method Set worksheet = excel.Worksheets.Item(2)

AE6382

Creating a COM Object Instance

Scripting languages have a mechanism for instantiating a COM classPerl: use Win32::OLE; ... my $excel = Win32::OLE->new(Excel.Application); JScript: var excel = new ActiveXObject(Excel.Application); VBScript: Dim excel Set excel = CreateObject(Excel.Application); Python: import win32com.client ... excel = win32com.client.Dispath(Excel.Application);

AE6382

Creating a COM Object Instance

Once top level object has been created the remaining hierarchy is accessed as per the languages normal object mechanism Tcl and Ruby can also instantiate COM objects

AE6382

Object Models

Every COM enabled Windows application has an object model Requires knowledge of object model to access application Discovering the object model

Use documentation (Office is documented) Use an object browser and trial and error

ActiveState Perl includes a simple Object Browser Visual Studio include an Object Browser

AE6382

Example - Perl#!/usr/bin/perl use strict; use use use use Win32::OLE qw(in with); Win32::OLE::Const 'Microsoft Excel'; Win32::OLE::Variant; Win32::OLE::NLS qw(:LOCALE :DATE);

# Program dies on errors $Win32::OLE::Warn = 3; # The use of ' rather than " is noted my $excel_file = 'c:\latham\ae8801d\perltut.xls'; # Create a connection to Excel # Try to use an existing object else create a new object my $Excel = Win32::OLE->GetActiveObject('Excel.Application') || Win32::OLE->new('Excel.Application','Quit'); print "ERROR: ",$Win32::OLE::LastError,"\n" if $Win32::OLE::LastError; # Turn off any alter boxes (such as the SaveAs response) $Excel->{DisplayAlerts} = 0; # Make Excel visible on the desktop $Excel->{Visible} = 1; # Add a workbook and save the file my $Book = $Excel->Workbooks->Add(); $Book->SaveAs($excel_file); # To open an existing file replace above with # my $Book = $Excel->Workbooks->Open($excel_file);

AE6382

Example Perl# Create a reference to a worksheet my $Sheet = $Book->Worksheets('Sheet1'); $Sheet->Activate(); $Sheet->{Name} = "sample_sheet"; # Insert some data into the worksheet my ($mday,$mon,$year) = (localtime(time))[3,4,5]; $year += 1900; my $str = $mon.'/'.$mday.'/'.$year; $Sheet->Range("a1")->{Value} = $str; $Sheet->Range("c1")->{Value} = "This is a long piece of text"; # Save $Book->SaveAs($excel_file); # Set cell colors via a loop foreach my $y (1..56) { my $range = 'b'.$y; $Sheet->Range($range)->Interior->{ColorIndex} = $y; $Sheet->Range($range)->{Value} = $y } # Re-format existing cell my $range = 'A1'; $Sheet->Range($range)->Interior->{ColorIndex} = 27; $Sheet->Range($range)->Font->{FontStyle} = "Bold"; $Sheet->Range($range)->{HorizontalAlignment} = xlHAlignCenter; # Set column widths my @columnheaders = qw(A:B); foreach my $range (@columnheaders) { $Sheet->Columns($range)->AutoFit(); } $Sheet->Columns("c")->{ColumnWidth} = 56;

AE6382

Example - Perl# Insert borders around cells my @edges = qw(xlEdgeBottom xlEdgeLeft xlEdgeRight xlEdgeTop xlInsideHorizontal xlInsideVertical); $range = "b1:c56"; foreach my $edge (@edges) { with (my $Borders = $Sheet->Range($range)->Borders(eval($edge)), LineStyle => xlContinuous, Weight => xlThin, ColorIndex => 1); } # Insert a picture my $picture1 = $Excel->Worksheets('Sheet2')->Shapes->AddPicture('c:\latham\ae8801d\image.jpg',-1,-1,0,0,200,200); $Excel->Worksheets('Sheet2')->{Name} = "B-17"; #$picture1->{Left} = 100; #$picture1->{Top} = 100; # Save $Book->SaveAs($excel_file); # Create a chart my $Sheet3 = $Excel->Worksheets('Sheet3'); my $Chart1 = $Sheet3->ChartObjects->Add(200,200,200,200); $Sheet3->{Name} = "Chart Example"; $Chart1->Chart->ChartWizard({Source => $Sheet3->Cells(1)}); $Chart1->Chart->SeriesCollection(1)->{Values} = [19,3,24,56,34,33,16,10,3,100]; # Print a list of the worksheets foreach my $Sheet (in $Book->{Worksheets}) { print "Worksheet:\t",$Sheet->{Name},"\n"; } print "Ready to quit"; ; exit;

AE6382

Example - JScript// var fso = new ActiveXObject("Scripting.FileSystemObject"); var excel = new ActiveXObject("Excel.Application"); excel.DisplayAlerts = 0; excel.Visible = 1; var book = excel.Workbooks.Add(); var sheet = book.Worksheets("Sheet1"); sheet.Activate(); sheet.Name = "sample sheet"; var wk2 = excel.Worksheets("Sheet2"); var pic1 = wk2.Shapes.AddPicture("c:\\latham\\ae8801d\\image.jpg",-1,-1,100.,100.,100.,50.); wk2.Name = "B-17"; pic1.Left = 100; pic1.Top = 100; WScript.Echo("Hello"); WScript.Sleep(2000); excel.Worksheets(1).Activate(); WScript.Sleep(2000); excel.Worksheets(2).Activate(); WScript.Sleep(2000); excel.Worksheets(3).Activate(); WScript.Sleep(2000); //var stdout = WScript.StdOut; //var stdin = WScript.StdIn; //var answer = stdin.ReadLine(); //stdout.WriteLine(answer); excel.Quit(); // var in = File("stdin"); // fgets(in);

AE6382

Example - Pythonimport win32com.client excel = win32com.client.Dispatch("Excel.Application","Quit") excel.DisplayAlerts = 0 excel.Visible = 1 book = excel.Workbooks.Add() sheet = book.Worksheets("Sheet1") sheet.Activate() sheet.Name = "sample sheet" picture = excel.Worksheets("Sheet2").Shapes.AddPicture("c:\\latham\\ae8801d\\image.jpg",-1,-1,100.,100.,100.,50.) excel.Worksheets("Sheet2").Name = "B-17" picture.Left = 100 picture.Top = 100 # Create a chart #sheet = excel.Worksheets('Sheet3'); #chart1 = sheet.ChartObjects.Add(200,200,200,200); #sheet.Name = "Chart Example"; #chart1.Chart.ChartWizard({Source => $Sheet3->Cells(1)}); #chart1.Chart.SeriesCollection(1)->{Values} = [19,3,24,56,34,33,16,10,3,100]; print "Hello from excel1.py" answer = raw_input("Quit ? ") excel.Quit();

AE6382