ae6382 introduction to scripting ae 6382. what is a scripting l scripting is the process of...

67
AE6382 Introduction to Scripting AE 6382

Post on 19-Dec-2015

260 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: AE6382 Introduction to Scripting AE 6382. What is a scripting l Scripting is the process of programming using a scripting language l A scripting language,

AE6382

Introduction to Scripting

AE 6382

Page 2: AE6382 Introduction to Scripting AE 6382. What is a scripting l Scripting is the process of programming using a scripting language l A scripting language,

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

Page 3: AE6382 Introduction to Scripting AE 6382. What is a scripting l Scripting is the process of programming using a scripting language l A scripting language,

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

Page 4: AE6382 Introduction to Scripting AE 6382. What is a scripting l Scripting is the process of programming using a scripting language l A scripting language,

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 Applications

Page 5: AE6382 Introduction to Scripting AE 6382. What is a scripting l Scripting is the process of programming using a scripting language l A scripting language,

AE6382

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, …)

Windows cmd/command have no programming constructs Windows PowerShell (4Q2006) will have extensive scripting

based on C# language

Page 6: AE6382 Introduction to Scripting AE 6382. What is a scripting l Scripting is the process of programming using a scripting language l A scripting language,

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

JavaScript / Jscript / ECMAScript 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

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

Page 7: AE6382 Introduction to Scripting AE 6382. What is a scripting l Scripting is the process of programming using a scripting language l A scripting language,

AE6382

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

Page 8: AE6382 Introduction to Scripting AE 6382. What is a scripting l Scripting is the process of programming using a scripting language l A scripting language,

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 1980’s

Python (also Jython) An object oriented language with some procedure traits Extensible A format based syntax Developed in early 1990’s

Page 9: AE6382 Introduction to Scripting AE 6382. What is a scripting l Scripting is the process of programming using a scripting language l A scripting language,

AE6382

Scripting Languages

Ruby An object oriented language Extensible C like syntax with minimal symbols (no {} () …) Developed in early 1990’s

TCL – Tool Command Language A procedural language Extensible A stack evaluation syntax, similar to Lisp (lots of []) Developed as an embeddable scripting language Developed in late 1980’s

Page 10: AE6382 Introduction to Scripting AE 6382. What is a scripting l Scripting is the process of programming using a scripting language l A scripting language,

AE6382

Scripting Languages

Other niche scripting languages BeanShell

– Makes it possible to use Java as a scripting language REXX

– C-like, objects, cross-platform, has a Java version

Page 11: AE6382 Introduction to Scripting AE 6382. What is a scripting l Scripting is the process of programming using a scripting language l A scripting language,

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 Pros

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 Windows

Page 12: AE6382 Introduction to Scripting AE 6382. What is a scripting l Scripting is the process of programming using a scripting language l A scripting language,

AE6382

Perl

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

Page 13: AE6382 Introduction to Scripting AE 6382. What is a scripting l Scripting is the process of programming using a scripting language l A scripting language,

AE6382

Perl

Has 3 classes of variables $var - scalar (integer, real, string, ...) @var - array of scalars, $var[0] %var - 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 { ... }

Page 14: AE6382 Introduction to Scripting AE 6382. What is a scripting l Scripting is the process of programming using a scripting language l A scripting language,

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)

The usual loop statements for for each while

Functions and methods are defined similarly sub name (…) { … }

Page 15: AE6382 Introduction to Scripting AE 6382. What is a scripting l Scripting is the process of programming using a scripting language l A scripting language,

AE6382

Perl

Loop statements

for ($i=0 ; $i < 10 ; $i++) { printf “i=%4d\n”,$i;}

while (<STDIN>) { print;}

@list = (0,5,8,12);foreach $value (@list) { print “Value=$value\n”;}

foreach $value (0,5,8,12) { print “Value=$value\n”;}

%hash = (part1=>0,part3=>70,part2=>4);foreach $key (sort keys %hash) { print “Value=$hash{$key}\n”;}

Page 16: AE6382 Introduction to Scripting AE 6382. What is a scripting l Scripting is the process of programming using a scripting language l A scripting language,

AE6382

Perl

Logical statements

if ($i == 1) { print “i=$i\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”;}

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

Page 17: AE6382 Introduction to Scripting AE 6382. What is a scripting l Scripting is the process of programming using a scripting language l A scripting language,

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

Page 18: AE6382 Introduction to Scripting AE 6382. What is a scripting l Scripting is the process of programming using a scripting language l A scripting language,

AE6382

Perl

Support for objects use Modulename; (include class definition) $var = Modulename::new(); (instantiate object) $var->method(...); (invoke method) $var->{property}; (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.

Page 19: AE6382 Introduction to Scripting AE 6382. What is a scripting l Scripting is the process of programming using a scripting language l A scripting language,

AE6382

M/S Scripting Documentation

Script56.chm is the Windows scripting documentation file

Local copy http://www.ae.gatech.edu/classes/ae6382/MS_scripting/

Page 20: AE6382 Introduction to Scripting AE 6382. What is a scripting l Scripting is the process of programming using a scripting language l A scripting language,

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

Pros Its syntax is very much like C It has support for objects

Cons Limited availability Has limited access to host system (security feature)

Page 21: AE6382 Introduction to Scripting AE 6382. What is a scripting l Scripting is the process of programming using a scripting language l A scripting language,

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 (...) { ... }

Page 22: AE6382 Introduction to Scripting AE 6382. What is a scripting l Scripting is the process of programming using a scripting language l A scripting language,

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]);}

Page 23: AE6382 Introduction to Scripting AE 6382. What is a scripting l Scripting is the process of programming using a scripting language l A scripting language,

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”);}

Page 24: AE6382 Introduction to Scripting AE 6382. What is a scripting l Scripting is the process of programming using a scripting language l A scripting language,

AE6382

JavaScript / JScript

Regular Expression Support

var 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); }}

Page 25: AE6382 Introduction to Scripting AE 6382. What is a scripting l Scripting is the process of programming using a scripting language l A scripting language,

AE6382

JavaScript / JScript

Regular Expression Support

var 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

Page 26: AE6382 Introduction to Scripting AE 6382. What is a scripting l Scripting is the process of programming using a scripting language l A scripting language,

AE6382

JavaScript / JScript

Object support var obj = new Object(); (instantiate object) obj.method(...); (invoke method) obj.property; (access property) obj[“property”]; (access property)

Page 27: AE6382 Introduction to Scripting AE 6382. What is a scripting l Scripting is the process of programming using a scripting language l A scripting language,

AE6382

M/S Scripting Documentation

Script56.chm is the Windows scripting documentation file

Local copy http://www.ae.gatech.edu/classes/ae6382/MS_scripting/

Page 28: AE6382 Introduction to Scripting AE 6382. What is a scripting l Scripting is the process of programming using a scripting language l A scripting language,

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

Pros Simple syntax (Basic) Has support for objects

Cons Windows only

Page 29: AE6382 Introduction to Scripting AE 6382. What is a scripting l Scripting is the process of programming using a scripting language l A scripting language,

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

Page 30: AE6382 Introduction to Scripting AE 6382. What is a scripting l Scripting is the process of programming using a scripting language l A scripting language,

AE6382

VBScript

Loop statements

Dim ii = 0For i=0 To 9 Step 1 WScript.StdOut.WriteLine "i=" & iNext

Do While Not WScript.StdIn.AtEndOfStream Dim line line = WScript.StdIn.ReadLine() WScript.StdOut.WriteLine(line)Loop

Dim d 'Create a variable Set d = CreateObject("Scripting.Dictionary") d.Add "0", "Athens" 'Add some keys and items d.Add "1", "Belgrade" d.Add "2", "Cairo"

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

Do Until WScript.StdIn.AtEndOfStream Dim line line = WScript.StdIn.ReadLine() WScript.StdOut.WriteLine(line)Loop

Page 31: AE6382 Introduction to Scripting AE 6382. What is a scripting l Scripting is the process of programming using a scripting language l A scripting language,

AE6382

VBScript

Logical statements

If i = 5 Then WScript.StdOut.WriteLine “Value is “ & iEnd If

If i = 1 Then WScript.StdOut.WriteLine“Group 1”Else WScript.StdOut.WriteLine “Unknown group”End If

If i = 1 Then WScript.StdOut.WriteLine “Group 1”ElseIf i = 2 Then WScript.StdOut.WriteLine “Group 2”ElseIf i = 3 Then WScript.StdOut.WriteLine “Group 3”Else WScript.StdOut.WriteLine “Unknown group”End If

Page 32: AE6382 Introduction to Scripting AE 6382. What is a scripting l Scripting is the process of programming using a scripting language l A scripting language,

AE6382

VBScript

Regular Expression Support

Dim reSet re = New RegExpre.Pattern = ".*error.*"re.IgnoreCase = TrueDo While Not WScript.StdIn.AtEndOfStream Dim line line = WScript.StdIn.Readline If re.Test(line) Then WScript.StdOut.WriteLine line End IfLoop

Page 33: AE6382 Introduction to Scripting AE 6382. What is a scripting l Scripting is the process of programming using a scripting language l A scripting language,

AE6382

VBScript

Regular Expression SupportDim lineDim iDim matchDim re1, re2, matches, submatchesDim 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 RegExpset re2 = New RegExpre1.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 IfNext

' 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

Page 34: AE6382 Introduction to Scripting AE 6382. What is a scripting l Scripting is the process of programming using a scripting language l A scripting language,

AE6382

VBScript

Object support Set obj = New Object (instantiate object) obj.method(...) (invoke method) obj.property (access property)

Page 35: AE6382 Introduction to Scripting AE 6382. What is a scripting l Scripting is the process of programming using a scripting language l A scripting language,

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

Pros Interpreter has a small footprint Easily embedded Extensible using C

Cons Strange syntax

Page 36: AE6382 Introduction to Scripting AE 6382. What is a scripting l Scripting is the process of programming using a scripting language l A scripting language,

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

Page 37: AE6382 Introduction to Scripting AE 6382. What is a scripting l Scripting is the process of programming using a scripting language l A scripting language,

AE6382

Tcl

Loop statements

for (set i 0} {$i < 10} {incr i 3} { lappend aList $i}set aList

set i 1foreach value {1 3 5 7 11 13 17 19 23} { set i [expr $i * $value]}set i

foreach x [list $a $b [foo]] { puts stdout “x = $x”}

set i 1while {$i <= 10} { set product [expr $product * $i] incr i}set product

Page 38: AE6382 Introduction to Scripting AE 6382. What is a scripting l Scripting is the process of programming using a scripting language l A scripting language,

AE6382

Tcl

Logical statements

if {$i == 5} { puts stdout “Equality failed”}

if {i == 1} { puts stdout “Group 1”} else { puts stdout “Unknown group”}

if {i == 1} { puts tdout “Group 1”} elseif (i == 2) { puts tdout “Group 2”} elseif (i == 3) { puts stdout “Group 3”} else { puts stdout “Unknown group”}

Page 39: AE6382 Introduction to Scripting AE 6382. What is a scripting l Scripting is the process of programming using a scripting language l A scripting language,

AE6382

Tcl

Logical statements

if {$x == 0} { puts stderr “Divide by zero”

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”);}

Page 40: AE6382 Introduction to Scripting AE 6382. What is a scripting l Scripting is the process of programming using a scripting language l A scripting language,

AE6382

Python

General purpose scripting language Available on most platforms

On Unix/Linux it runs standalone using #! script file convention In Windows it can run standalone an is also available as an

ActiveX scripting engine

Designed from the start as an object oriented language Pros

Has wide support and runs everywhere Jython is a version coded in Java and can access Java classes

directly

Cons Has a syntax based on formatting

Page 41: AE6382 Introduction to Scripting AE 6382. What is a scripting l Scripting is the process of programming using a scripting language l A scripting language,

AE6382

Python

Variables Typeless Scalar name = “sam” Lists names = [“sam”, “bill”, “ted”] Tuples (1,2,5,20) Dictionaries rooms = {“sam”:302,”bill”:305,”ted”:401}

Namespace separation (packages) Block structure is indicated by spacing Strings are immutable

Page 42: AE6382 Introduction to Scripting AE 6382. What is a scripting l Scripting is the process of programming using a scripting language l A scripting language,

AE6382

Python

Loop statementsCount = 0for line in range(0..10): count = count + 1 print count

Count = 10While count < 10: count = count + 1

Page 43: AE6382 Introduction to Scripting AE 6382. What is a scripting l Scripting is the process of programming using a scripting language l A scripting language,

AE6382

Python

Conditional statementsValue = 2if value%2 == 0: print “Value is even”else: print “Value is odd”

Page 44: AE6382 Introduction to Scripting AE 6382. What is a scripting l Scripting is the process of programming using a scripting language l A scripting language,

AE6382

Python

Object support Class definition

Object instantiation– obj = Special()

Method invocation– obj.method1(…)

class Special: def __init__(self): self.count = 0

def method1(self,…): … def method2(self,…): …

Page 45: AE6382 Introduction to Scripting AE 6382. What is a scripting l Scripting is the process of programming using a scripting language l A scripting language,

AE6382

Ruby

General purpose scripting language Available on most platforms

On Unix/Linux it runs standalone using #! script file convention

Designed from the start as an object oriented language Pros

Is becoming widely used Has a more conventional syntax without the clutter of C and Perl

Cons Is relatively new on scene

Page 46: AE6382 Introduction to Scripting AE 6382. What is a scripting l Scripting is the process of programming using a scripting language l A scripting language,

AE6382

Ruby

Variables Typeless $global_variable @@class_variable @instance_variable local_variable

Types of variables Scalar name = “sam” Arrays names = [“sam”, “bill”, “ted”], names[2] Hashes rooms = {“sam”:302,”bill”:305,”ted”:401},

rooms{“sam}

Namespace separation

Page 47: AE6382 Introduction to Scripting AE 6382. What is a scripting l Scripting is the process of programming using a scripting language l A scripting language,

AE6382

Ruby

Loop statementscount = 1while count < 10 count = count + 1end

count = 1until count == 10 count = count + 1end

loop count = count + 1end

count = 1begin count = count + 1end while count < 10

count = 1begin count = count + 1end until count == 10

Page 48: AE6382 Introduction to Scripting AE 6382. What is a scripting l Scripting is the process of programming using a scripting language l A scripting language,

AE6382

Ruby

Conditional statementsvalue = 6if value%3 == 0 print “remainder 0”elsif value%3 == 1 print “remainder 1”else print “remainder 2”end

value = 6unless value == 6 print “value is not 6end

print “stop” if value == 0

Page 49: AE6382 Introduction to Scripting AE 6382. What is a scripting l Scripting is the process of programming using a scripting language l A scripting language,

AE6382

Ruby

Object support Class definition

Object instantiation– obj = special.new

Method invocation– obj.method1(…)

class special def initialize … end def method1(…) … end def method2(…) … endend

Page 50: AE6382 Introduction to Scripting AE 6382. What is a scripting l Scripting is the process of programming using a scripting language l A scripting language,

AE6382

Scripting in Unix

The usual method of executing a script in Unix/Linux is to include the location of the interpreter on line 1 #!/usr/bin/perl #!/usr/bin/sh

The script must be readable and executable by the user attempting to run it

Page 51: AE6382 Introduction to Scripting AE 6382. What is a scripting l Scripting is the process of programming using a scripting language l A scripting language,

AE6382

Scripting in Windows

The usual method of executing a script in windows is to associate a file extension with the interpreter file.pl Perl script file.py Python script file.cmd Command file

Alternate methods are used for scripts that are to be run by resident ActiveX scripting engines wscript cscript wsf – Windows Scripting File hta – HTML Applications

Page 52: AE6382 Introduction to Scripting AE 6382. What is a scripting l Scripting is the process of programming using a scripting language l A scripting language,

AE6382

M/S Scripting Documentation

Script56.chm is the Windows scripting documentation file

Local copy http://www.ae.gatech.edu/classes/ae6382/MS_scripting/

Page 53: AE6382 Introduction to Scripting AE 6382. What is a scripting l Scripting is the process of programming using a scripting language l A scripting language,

AE6382

Scripting in Windows

sample1.js execute from cmd prompt> cscript sample1.js

// Get the stdin and stdout descriptors// The WScript object is created automatically by WSHvar stdin = WScript.StdIn; // propertiesvar stdout = WScript.StdOut;

// Get the value to pass to programstdout.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/Ovar WshScriptExec = WshShell.Exec("program1");

// Write to the running programs stdioWshScriptExec.StdIn.WriteLine(" "+i+" "+j);

// Wait for the running program to exitwhile (WshScriptExec.Status != 1) { ;}

// Read from the running programs stdoutvar output = WshScriptExec.StdOut.ReadLine();stdout.WriteLine("Output from program: "+output);

Page 54: AE6382 Introduction to Scripting AE 6382. What is a scripting l Scripting is the process of programming using a scripting language l A scripting language,

AE6382

Scripting in Windows

sample1.wsf execute from cmd prompt> sample1.wsf

<job id="sample1"> <script language="JScript"> // 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); </script></job>

Page 55: AE6382 Introduction to Scripting AE 6382. What is a scripting l Scripting is the process of programming using a scripting language l A scripting language,

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

Page 56: AE6382 Introduction to Scripting AE 6382. What is a scripting l Scripting is the process of programming using a scripting language l A scripting language,

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

Page 57: AE6382 Introduction to Scripting AE 6382. What is a scripting l Scripting is the process of programming using a scripting language l A scripting language,

AE6382

Objects in COM

A class defines an object Properties are variables Methods are functions

When a class is instantiated an object is created 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

Page 58: AE6382 Introduction to Scripting AE 6382. What is a scripting l Scripting is the process of programming using a scripting language l A scripting language,

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 application’s 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

Page 59: AE6382 Introduction to Scripting AE 6382. What is a scripting l Scripting is the process of programming using a scripting language l A scripting language,

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)

Page 60: AE6382 Introduction to Scripting AE 6382. What is a scripting l Scripting is the process of programming using a scripting language l A scripting language,

AE6382

Creating a COM Object Instance

Scripting languages have a mechanism for instantiating a COM class

Perl:

use Win32::OLE;...my $excel = Win32::OLE->new(‘Excel.Application’);

JScript:

var excel = new ActiveXObject(“Excel.Application”);

VBScript:

Dim excelSet excel = CreateObject(“Excel.Application”);

Python:

import win32com.client...excel = win32com.client.Dispath(“Excel.Application”);

Page 61: AE6382 Introduction to Scripting AE 6382. What is a scripting l Scripting is the process of programming using a scripting language l A scripting language,

AE6382

Creating a COM Object Instance

Once top level object has been created the remaining hierarchy is accessed as per the language’s normal object mechanism

Tcl and Ruby can also instantiate COM objects

Page 62: AE6382 Introduction to Scripting AE 6382. What is a scripting l Scripting is the process of programming using a scripting language l A scripting language,

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

Page 63: AE6382 Introduction to Scripting AE 6382. What is a scripting l Scripting is the process of programming using a scripting language l A scripting language,

AE6382

Example - Perl

#!/usr/bin/perl

use strict;

use Win32::OLE qw(in with);use Win32::OLE::Const 'Microsoft Excel';use Win32::OLE::Variant;use Win32::OLE::NLS qw(:LOCALE :DATE);

# Program dies on errors$Win32::OLE::Warn = 3;

# The use of ' rather than " is notedmy $excel_file = 'c:\latham\ae8801d\perltut.xls';

# Create a connection to Excel# Try to use an existing object else create a new objectmy $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 filemy $Book = $Excel->Workbooks->Add();$Book->SaveAs($excel_file);

# To open an existing file replace above with# my $Book = $Excel->Workbooks->Open($excel_file);

Page 64: AE6382 Introduction to Scripting AE 6382. What is a scripting l Scripting is the process of programming using a scripting language l A scripting language,

AE6382

Example – Perl

# Create a reference to a worksheetmy $Sheet = $Book->Worksheets('Sheet1');$Sheet->Activate();$Sheet->{Name} = "sample_sheet";

# Insert some data into the worksheetmy ($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 loopforeach my $y (1..56) {

my $range = 'b'.$y;$Sheet->Range($range)->Interior->{ColorIndex} = $y;$Sheet->Range($range)->{Value} = $y

}

# Re-format existing cellmy $range = 'A1';$Sheet->Range($range)->Interior->{ColorIndex} = 27;$Sheet->Range($range)->Font->{FontStyle} = "Bold";$Sheet->Range($range)->{HorizontalAlignment} = xlHAlignCenter;

# Set column widthsmy @columnheaders = qw(A:B);foreach my $range (@columnheaders) {

$Sheet->Columns($range)->AutoFit();}$Sheet->Columns("c")->{ColumnWidth} = 56;

Page 65: AE6382 Introduction to Scripting AE 6382. What is a scripting l Scripting is the process of programming using a scripting language l A scripting language,

AE6382

Example - Perl

# Insert borders around cellsmy @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 picturemy $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 chartmy $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 worksheetsforeach my $Sheet (in $Book->{Worksheets}) {

print "Worksheet:\t",$Sheet->{Name},"\n";}

print "Ready to quit";<>;exit;

Page 66: AE6382 Introduction to Scripting AE 6382. What is a scripting l Scripting is the process of programming using a scripting language l A scripting language,

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);

Page 67: AE6382 Introduction to Scripting AE 6382. What is a scripting l Scripting is the process of programming using a scripting language l A scripting language,

AE6382

Example - Python

import win32com.clientexcel = win32com.client.Dispatch("Excel.Application","Quit")excel.DisplayAlerts = 0excel.Visible = 1book = 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 = 100picture.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();