Professional Documents
Culture Documents
AE 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
AE6382
Scripting Features
A variable may during the course of execution contain strings, integers, and objects
Scripting languages frequently build into the basic language higher order abstractions
Most scripting interpreters can be embeddedt into other programs to provide scripting capability within that program
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
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 1990s
AE6382
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
AE6382
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 Windows
AE6382
Pros
Perl
Cons
Can be difficult for beginners to learn Variable naming scheme is initially confusing There is a high learning curve
AE6382
Perl
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 () { }
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; } %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 statements
if ($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
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
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
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 statements
var 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
AE6382
JavaScript / JScript
// 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
AE6382
Script56.chm is the Windows scripting documentation file Local copy http://www.ae.gatech.edu/classes/ae6 382/MS_scripting/
AE6382
VBScript
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 statements
Dim 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
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
AE6382
VBScript
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
AE6382
VBScript
Object support
AE6382
Tcl
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 statements
for (set i 0} {$i < 10} {incr i 3} { lappend aList $i } set aList set i 1 while {$i <= 10} { set product [expr $product * $i] incr i } set product set i 1 foreach 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 }
AE6382
Tcl
Logical statements
if {$i == 5} { puts stdout Equality failed } if {i == 1} { puts stdout Group 1 } else { puts stdout Unknown group }
AE6382
Tcl
Logical statements
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
Python
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
Has wide support and runs everywhere Jython is a version coded in Java and can access Java classes directly Has a syntax based on formatting
Cons
AE6382
Python
Variables
Namespace separation (packages) Block structure is indicated by spacing Strings are immutable
AE6382
Python
Loop statements
Count = 0 for line in range(0..10): count = count + 1 print count
AE6382
Python
Conditional statements
Value = 2 if value%2 == 0: print Value is even else: print Value is odd
AE6382
Python
Object support
Class definition
class Special: def __init__(self): self.count = 0 def method1(self,): def method2(self,):
Object instantiation
Method invocation
AE6382
Ruby
Is becoming widely used Has a more conventional syntax without the clutter of C and Perl Is relatively new on scene
Cons
AE6382
Ruby
Variables
Typeless $global_variable @@class_variable @instance_variable local_variable Scalar Arrays Hashes rooms{sam} name = sam names = [sam, bill, ted], names[2] rooms = {sam:302,bill:305,ted:401},
Types of variables
Namespace separation
AE6382
Ruby
Loop statements
count = 1 while count < 10 count = count + 1 end count = 1 begin count = count + 1 end while count < 10 count = 1 until count == 10 count = count + 1 end count = 1 begin count = count + 1 end until count == 10 loop count = count + 1 end
AE6382
Ruby
Conditional statements
value = 6 if value%3 == 0 print remainder 0 elsif value%3 == 1 print remainder 1 else print remainder 2 end value = 6 unless value == 6 print value is not 6 end
AE6382
Ruby
Object support
Class definition
class def end def end def end end special initialize
method1()
method2()
Object instantiation
Method invocation
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
AE6382
Scripting in Windows
The usual method of executing a script in windows is to associate a file extension with the interpreter
Alternate methods are used for scripts that are to be run by resident ActiveX scripting engines
AE6382
Script56.chm is the Windows scripting documentation file Local copy http://www.ae.gatech.edu/classes/ae6 382/MS_scripting/
AE6382
Scripting in Windows
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
<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>
AE6382
WSH is the context within which VBScript and JScript run PerlScript and PythonScript are also available Start WSH scripts using cscript or wscript
The WSF format can contain several scripts in one text file
AE6382
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
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
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
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
AE6382
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 - Python
import 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