Wednesday, March 30, 2005
Basic Calculator Application
With the intension of building simple parser I made a move to get calculator application that supports variables and dynamic value fetch etc. Well I am falling short of text to put into here to describe my excitement. I am putting below the source code so that you can try it out. The application is written in C#.
Feedback and Suggestions are most welcome (Use comments to express them). Download
Feedback and Suggestions are most welcome (Use comments to express them). Download
View Calculator Code
Hide Calculator Code
/**
* Basic Calculator Application
* Author: Prasad.A
*/
using System;
using System.Collections;
namespace ConsoleCalculator {
/* Basic Calculator Class */
public class BaseCalculator {
/* Dictionary to store variables and its values */
private IDictionary _dictionary = null;
/* Stack to carry out the operations */
private Stack operationStack = null;
/* Default Constructor */
public BaseCalculator() {
this._dictionary = new Hashtable();
Console.WriteLine("Basic Calculator Application");
Console.WriteLine("Type 'quit' to terminate.");
}
/* Get the substring of the string */
private String GetSubString(String expression,int start,int end) {
return expression.Substring(start,(end-start));
}
/* Push element on to operation stack */
private void Push(Object element) {
operationStack.Push(element);
}
/* Pop element from the operation stack */
private Object Pop() {
if(operationStack.Count > 0) return operationStack.Pop();
return null;
}
/* Peek element from the operation stack */
private Object Peek() {
if(operationStack.Count > 0) return operationStack.Peek();
return null;
}
/* Evaluate the expression within '(' and ')' */
private void EvaluateSubExpression() {
Object element = Pop(); /* This is just behind ')' */
while(element != null && element.ToString().CompareTo("(") != 0) {
/* Get result from binary evaluation */
Object binaryEvaluation = BinaryEvaluate(element);
element = Pop(); /* This will be the operator for next iteration */
/* Did we get start of sub expression */
if(element.ToString().CompareTo("(")==0) {
/* Push the result and break out of loop */
Push(binaryEvaluation);
break;
}
/* Push back the operator that was popped */
Push(element);
/* Now one of the operand is the result itself */
element = binaryEvaluation;
}
}
/* Evaluate the expression */
private Object EvaluateExpression() {
Object result = null;
Object element = Pop(); /* This is operand two */
while(element!=null) {
/* Get result from binary evaluation */
result = BinaryEvaluate(element);
/* If we have reached end of stack, break */
if(Peek() == null) break;
/* Opearand two is result itself */
element = result;
}
return result;
}
/* Evaluate the binary expression, the input parameter is operand2,
* Get the operator element and operand1 from stack. If operator element
* or operand1 is not present do a unary operation else if operator element
* is = then do a assignment operation else do a binary evaluation.
*/
private Object BinaryEvaluate(Object operandTwo) {
Object evalBinary = new Object();
Object operatorElement = null;
Object operandOne = null;
if(Peek() != null &&
Peek().ToString().CompareTo("(")!=0)
operatorElement = Pop();
if(operatorElement != null &&
Peek() != null &&
Peek().ToString().CompareTo("(")!=0)
operandOne = Pop();
if(operatorElement!=null &&
operatorElement.ToString().CompareTo("=")!=0) {
operandTwo = GetObjectValue(operandTwo);
operandOne = GetObjectValue(operandOne);
}
if(operatorElement==null)
evalBinary = GetObjectValue(operandTwo);
else if(operandOne==null) {
if(operatorElement.ToString().CompareTo("+")==0)
evalBinary = (+1.0)*double.Parse(operandTwo.ToString());
else if(operatorElement.ToString().CompareTo("-")==0)
evalBinary = (-1.0)*double.Parse(operandOne.ToString());
}
else {
switch(operatorElement.ToString()) {
case "+":
evalBinary = double.Parse(operandOne.ToString())+
double.Parse(operandTwo.ToString()); break;
case "-":
evalBinary = double.Parse(operandOne.ToString())-
double.Parse(operandTwo.ToString()); break;
case "*":
evalBinary = double.Parse(operandOne.ToString())*
double.Parse(operandTwo.ToString()); break;
case "/":
evalBinary = double.Parse(operandOne.ToString())/
double.Parse(operandTwo.ToString()); break;
case "=":
SetIdValue(operandOne.ToString(),operandTwo.ToString());
evalBinary = null; break;
}
}
return evalBinary;
}
/* Parse the input string and evaluate as and when required */
private Object parse(String expression) {
operationStack = new Stack();
int parsePointer = 0; /* Points to beginning of token */
bool inIdentifier = false,inNumber = false;
for(int index=0; index < expression.Length; ++index) {
char ch=expression[index];
/* We got a identifier or number delimiter */
if(ch == ' ' || ch == '\t') {
if(inIdentifier) {
Push(GetSubString(expression,parsePointer,index));
parsePointer = index+1;
inIdentifier = false;
}
if(inNumber) {
Push(GetSubString(expression,parsePointer,index));
parsePointer = index+1;
inNumber = false;
}
}
/* We got start of sub expression */
else if(ch=='(') {
Push(ch.ToString());
parsePointer = index+1;
}
/* We got end of sub expression */
else if(ch == ')') {
if(inIdentifier) {
Push(GetSubString(expression,parsePointer,index));
parsePointer = index+1;
inIdentifier = false;
}
if(inNumber) {
Push(GetSubString(expression,parsePointer,index));
parsePointer = index+1;
inNumber = false;
}
EvaluateSubExpression();
}
/* We got assignment operator */
else if(ch=='=') {
if(inIdentifier) {
Push(GetSubString(expression,parsePointer,index));
inIdentifier = false;
}
Push(ch.ToString());
parsePointer = index+1;
}
/* We got arithmetic operator */
else if(isOperator(ch)) {
if(inIdentifier) {
Push(GetSubString(expression,parsePointer,index));
inIdentifier = false;
}
if(inNumber) {
Push(GetSubString(expression,parsePointer,index));
inNumber = false;
}
Push(ch.ToString());
parsePointer = index+1;
}
/* We got a letter and we are not in identifier */
else if(Char.IsLetter(ch) && !inIdentifier) {
inIdentifier = true;
}
/* We got a digit and we are not in number */
else if(Char.IsDigit(ch) && !inNumber) {
inNumber = true;
}
/* We got a decimal point */
else if(ch=='.') {
if(index < expression.Length-1 &&
!Char.IsDigit(expression[index+1])) {
Push(GetSubString(expression,parsePointer,index));
parsePointer = index+1;
inNumber = false;
}
}
/* We are in identifier and we got a identifier delimiter */
else if(inIdentifier && isIdDelimiter(ch)) {
Push(GetSubString(expression,parsePointer,index));
parsePointer = index+1;
inIdentifier = false;
}
/* We are in number and we got a number delimiter */
else if(inNumber && isNumberDelimiter(ch)) {
Push(GetSubString(expression,parsePointer,index));
parsePointer = index+1;
inNumber = false;
}
}
/* Are we still in identifier */
if(inIdentifier)
Push(GetSubString(expression,parsePointer,expression.Length));
/* Are we still in number */
else if(inNumber)
Push(GetSubString(expression,parsePointer,expression.Length));
/* Let us return the result of expression */
return EvaluateExpression();
}
/* Decide on the identifier delimiter */
private bool isIdDelimiter(char delim) {
if(delim=='.'||delim=='('||delim==')') return true;
return isOperator(delim);
}
/* Decide on the nubmer delimiter */
private bool isNumberDelimiter(char delim) {
if(delim=='('||delim==')') return true;
return Char.IsLetter(delim);
}
/* Decide on the operator */
private bool isOperator(char delim) {
if(delim=='+'||delim=='-'||delim=='*'||delim=='/'||delim=='=')
return true;
return false;
}
/* Get the value of input object
* return either number or variable value)
*/
private Object GetObjectValue(Object inputObject) {
Object valueObject = null;
try {
valueObject = GetNumberObject(inputObject.ToString());
} catch(FormatException fe) {
valueObject = GetIdValue(inputObject.ToString());
}
return valueObject;
}
/* Return the numeric representation of input string */
private Object GetNumberObject(String inputString) {
Object numberObject = null;
try {
numberObject = int.Parse(inputString);
} catch(FormatException fei) {
try {
numberObject = double.Parse(inputString);
} catch(FormatException fed) {
throw new FormatException("Error! Illegal number format");
}
}
return numberObject;
}
/* Set the variable and its value in _dictionary */
private void SetIdValue(String id,String val) {
Object number = null;
try {
number = GetNumberObject(val);
} catch(FormatException fe) {
number = GetIdValue(val);
}
if(number != null) _dictionary[id] = number.ToString();
}
/* Get the value of the variable from _dictionary */
private Object GetIdValue(String id) {
Object idValue = _dictionary[id];
if(idValue != null) return idValue;
throw new Exception("Error! Variable '"+id+"' not yet defined");
}
/* Core function to keep the interaction alive */
public void RunCalculator() {
while(true) {
Console.Write(">>> ");
String input = Console.ReadLine();
if(input.CompareTo("quit")==0)
break;
try {
Object result = parse(input);
if(result != null)
Console.WriteLine(result.ToString());
} catch(Exception ex) {
Console.WriteLine(ex.Message);
}
}
}
}
/* A user class that contains the main function
* To give life to calculator */
public class UserCalculator {
public static void Main(string[] args) {
BaseCalculator bc = new BaseCalculator();
bc.RunCalculator();
}
}
}
Basic Calculator Application
Type 'quit' to terminate.
>>> a=10.5
>>> b
Error! Variable 'b' not yet defined
>>> b=20
>>> b
20
>>> c=a+b
>>> c
30.5
>>> d=10.1+(b*c)/a
>>> d
68.1952380952381
>>> quit
Friday, March 18, 2005
WordPress filter Colorizer (PraColorizer)
I have written filter plugin for WordPress that will colorize your java,c++,c,c# code that you will put in the post. You can download from here.
To know more about PraColorizer click here.
You can also get information at wp-plugins.net
To know more about PraColorizer click here.
You can also get information at wp-plugins.net
Thursday, March 17, 2005
pracut filter at wp-plugins.net
I have updated the pracut filter for wordpress at wp-plugins.net. To know more about pracut tag see this entry.
Tuesday, March 15, 2005
WordPress filter for pracut tag
Hey, I have written filter plugin for WordPress. You can download from here. To know more about pracut tag click here.
Wednesday, March 09, 2005
Toggle Content Display
I have been using a small snippet of my html design that uses css and javascript to toggle the display of content that is under it. I use it to toggle the source code, the output, etc. I am putting the html code under the toggle below, check it out and feel free use it.
View Html CodeHide Html Code<span id="vid"
style="text-decoration:underline;display:inline;cursor:pointer;color:blue;"
onclick="this.style.display='none';document.getElementById('hid').style.display='inline';
document.getElementById('sid').style.display='block';">
<b>View Html Code</b></span>
<span id="hid" style="text-decoration:underline;display:none;cursor:pointer;color:blue;"
onclick="this.style.display='none';document.getElementById('vid').style.display='inline';
document.getElementById('sid').style.display='none';">
<b>Hide Html Code</b></span>
<div id="sid" style="display: none;"><pre>
Here goes my content[ NOTE: Please take care keep the id (vid,hid,sid) unique ]
</pre></div>
Colorizer: For C#, Java, C, C++
This Colorizer is implemented in C#. The implementation of colorizer basically started of to be a good choice to demonstrate the use of regular expression (atleast the basic) and few useful syntax the C# provides, like inside the swtich statement, the handling of dictionary. You can use this colorizer to colorize the java, c, c++ or c# code. Before I end this entry let me tell one small thing [I used the same colorizer to colorize the source shown below :)]. Download
View Colorizer.csHide Colorizer.cs
// Author: Prasad.A
using System;
using System.Collections;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
namespace CSharpUtils {
// Class that describes keywords and creates a dictionary
// lookup depending on the language selection.
class CKeyword {
// Dictionary to lookup the keyword.
private IDictionary keydict = null;
// Java language keywords
protected string[] jkeywords = {
"abstract", "default", "goto", "package", "synchronized",
"boolean", "do", "if", "private", "this",
"break", "double", "implements", "protected","throw",
"byte", "else", "import", "public", "throws",
"case", "enum", "instanceof", "return", "transient",
"catch", "extends", "int", "short", "try",
"char", "final", "interface", "static", "void",
"class", "finally", "long", "strictfp", "volatile",
"const", "float", "native", "super", "while",
"continue", "for", "new", "switch"
};
// C# language keywords
protected string[] cskeywords = {
"abstract", "event", "new", "struct",
"as", "explicit", "null", "switch",
"base", "extern", "object", "this",
"bool", "false", "operator", "throw",
"break", "finally", "out", "true",
"byte", "fixed", "override", "try",
"case", "float", "params", "typeof",
"catch", "for", "private", "uint",
"char", "foreach", "protected","ulong",
"checked", "goto", "public", "unchecked",
"class", "if", "readonly", "unsafe",
"const", "implicit", "ref", "ushort",
"continue", "in", "return", "using",
"decimal", "int", "sbyte", "virtual",
"default", "interface","sealed", "volatile",
"delegate", "internal", "short", "void",
"do", "is", "sizeof", "while",
"double", "lock", "stackalloc",
"else", "long", "static",
"enum", "namespace","string"
};
// C language keywords
protected string[] ckeywords = {
"auto", "double", "int", "struct",
"break", "else", "long", "switch",
"case", "enum", "register", "typedef",
"char", "extern", "return", "union",
"const", "float", "short", "unsigned",
"continue", "for", "signed", "void",
"default", "goto", "sizeof", "volatile",
"do", "if", "static", "while"
};
// C++ language keywords
protected string[] cppkeywords = {
"asm", "auto", "bool", "break", "case",
"catch", "char", "class", "const", "continue",
"default", "delete", "do", "double", "else",
"enum", "explicit", "extern", "false", "float",
"for", "friend", "goto", "if", "inline",
"int", "long", "mutable", "namespace",
"new", "operator", "private", "protected", "public",
"register", "return", "short", "signed", "sizeof",
"static", "struct", "switch", "template", "this",
"throw", "true", "try", "typedef", "typeid",
"typename", "union", "unsigned", "using", "virtual",
"void", "volatile", "while"
};
// Default Language is C#
public CKeyword() { initKeyDict("c#"); }
// Set the user specified language
public CKeyword(string language) { initKeyDict(language); }
// Initialize the keyword lookup dictionary
public void initKeyDict(string language) {
string[] initKeywords = null;
if(language=="c#"||language==null) initKeywords = cskeywords;
else if(language=="java") initKeywords = jkeywords;
else if(language=="c") initKeywords = ckeywords;
else if(language=="c++") initKeywords = cppkeywords;
keydict = new Hashtable();
for(int i=0; i < initKeywords.Length; ++i) {
keydict[initKeywords[i]] = "";
}
}
// Check whether the given word is a keyword
protected bool isKeyword(String word) { return keydict.Contains(word); }
}
// Class that will do the coloring of input file
class Colorizer : CKeyword {
private bool inDocumentation = false; // Are we inside the documentation
private bool inComment = false; // Are we inside the comment
private string filename = null; // File under processing
private bool completeHtml = false; // Should the output be complete html
// Default constructor
public Colorizer() { }
// Constructor to set the language type and output type
public Colorizer(string language,bool completeHtml) : base(language) {
this.completeHtml = completeHtml;
}
// Actual function that will colorize the input file and dumps the
// output to output file (if null then standard output will be used)
public void colorize(string infile,string outfile) {
// Set the file name under process.
filename = infile;
StreamReader instream = new StreamReader(filename);
// Set the console output to file if outfile is specified
if(outfile != null) Console.SetOut(new StreamWriter(outfile));
// If output should be complete html put the headers
if(completeHtml) writeHtmlHeaders();
// Parse each line and the process it
for(string line; (line = instream.ReadLine()) != null; ) {
bool doParse = true;
while(doParse) {
IDictionary dictionary = parseLine(line);
dictionary["line"] = line;
line = processResult(dictionary);
if(line == null) doParse = false;
}
}
// If output is complete html put the footers
if(completeHtml) writeHtmlFooters();
// Close the output stream
if(outfile != null) Console.Out.Close();
}
// Write starting html tags
private void writeHtmlHeaders() {
Console.Write("<html><head><title>"+filename+"</title>");
Console.Write("<style type='text/css'>");
Console.Write(".body { font: 10pt Verdana, sans-serif; }");
Console.Write(".keyword { color: blue;} ");
Console.Write(".comment { color: green;} ");
Console.Write(".document { color: #777777;} ");
Console.Write(".string { color: brown;} ");
Console.Write("</style>");
Console.WriteLine("</head>");
Console.Write("<body><pre>");
}
// Write ending html tags
private void writeHtmlFooters() {
Console.Write("</pre></body></html>");
}
// Parse each line of input
private IDictionary parseLine(string line) {
// Core pattern that will break the line into token
string pattern = @"(/\*\*?)|(\*/)|(//)|(\w+)|([ \t\r\n]+)|("".*"")|([^*/\w\t\r\n ])|([/\*])";
// Get the token
Match match = Regex.Match(line,pattern);
// Set the result as dictionary
IDictionary dictionary = new Hashtable();
dictionary["index"] = match.Index;
dictionary["length"] = match.Length;
return dictionary;
}
// Process the match
private string processResult(IDictionary dictionary) {
int index = (int) dictionary["index"];
int length = (int) dictionary["length"];
string line = (string) dictionary["line"];
if(length==0) { Console.WriteLine(); return null; }
else {
return processToken(line.Substring(index,length),
line.Substring(index+length));
}
}
// Process the token
private string processToken(string token,string remenant) {
bool inline = true;
switch(token) {
case "/*":
inComment = true;
if(completeHtml) Console.Write("<span class='comment'>");
else Console.Write("<span style='{color:green;}'>");
Console.Write(convertToHtml(token));
break;
case "/**":
inDocumentation = true;
if(completeHtml) Console.Write("<span class='document'>");
else Console.Write("<span style='{color:#777777;}'>");
Console.Write(convertToHtml(token));
break;
case "*/":
Console.Write(token);
if(inComment || inDocumentation) Console.Write("</span>");
inComment = inDocumentation = false;
break;
case "//":
if(completeHtml) Console.Write("<span class='comment'>");
else Console.Write("<span style='{color:green;}'>");
Console.WriteLine(convertToHtml(token+remenant));
Console.Write("</span>");
remenant=null;
break;
default:
if(inComment || inDocumentation) Console.Write(token);
else {
if(base.isKeyword(token)) {
if(completeHtml)
Console.Write("<span class='keyword'>");
else Console.Write("<span style='{color:blue;}'>");
Console.Write(convertToHtml(token));
Console.Write("</span>");
}
else if(token.StartsWith("\"") && token.EndsWith("\"")) {
if(completeHtml)
Console.Write("<span class='string'>");
else Console.Write("<span style='{color:brown;}'>");
Console.Write(convertToHtml(token));
Console.Write("</span>");
}
else
Console.Write(convertToHtml(token));
}
break;
}
return remenant;
}
// Format the text to put as html
private StringBuilder convertToHtml(string text) {
StringBuilder sb = new StringBuilder(text);
sb = sb.Replace("<","<");
sb = sb.Replace(">",">");
return sb;
}
// Display the version and exit
private static void printVersion() {
Console.WriteLine("Colorizer, Version 1.0, Author: Prasad.A");
System.Environment.Exit(0);
}
// Display the help and exit
private static void printHelp() {
Console.WriteLine("Usage: ");
Console.WriteLine("mono Colorizer.exe [-l language] [-o outputfile] [--html] [--help,-h] [--version,-v] inputfile");
Console.WriteLine("-l: Language selection, one of them [c# java c c++]");
Console.WriteLine("-o: Output file name, (default to standard output)");
Console.WriteLine("--html: For complete html output.");
Console.WriteLine("-h, --help: This help.");
Console.WriteLine("-v, --version: Version and Author information.");
System.Environment.Exit(0);
}
private static String getLanguage(String language) {
String specifiedLang = language.ToLower();
if( String.Compare("c#",specifiedLang) == 0 ||
String.Compare("java",specifiedLang) == 0 ||
String.Compare("c",specifiedLang) == 0 ||
String.Compare("c++",specifiedLang) == 0 ) {
return specifiedLang;
} else {
Console.WriteLine("Unsupported language: "+language);
Console.WriteLine("Supported language: c#, java, c, c++");
System.Environment.Exit(1);
return null;
}
}
// Main function to run the Colorizer.
public static void Main(string[] args) {
string language = null;
string inputfile = null;
string outputfile = null;
bool completeHtml = false;
// Handle command line arguments
if(args.Length > 0) {
for(int i = 0; i < args.Length; ++i) {
switch(args[i]) {
case "-o":
if(i < args.Length-1) outputfile = args[++i];
else printHelp();
break;
case "-l":
if(i < args.Length-1) language = getLanguage(args[++i]);
else printHelp();
break;
case "--help": printHelp(); break;
case "-h": printHelp(); break;
case "--version": printVersion(); break;
case "-v": printVersion(); break;
case "--html": completeHtml = true; break;
default: inputfile = args[i]; break;
}
}
}
// If input file is not specified, print help and exit
if(inputfile == null) printHelp();
// Start the colorizer after initalization
Colorizer colorizer = new Colorizer(language,completeHtml);
colorizer.colorize(inputfile,outputfile);
}
}
}
Wednesday, March 02, 2005
xmllint --shell in Python
After looking at xmllint tool in linux and giving a small introductory talk on it I came to decision to start of its implementation in python that can serve as basic introduction to xml handling in python. For this I used minidom module of python's xml.dom library which is pretty simple to understand for the starters. The program I have desgined will implement very few option of xmllint --shell. This version of python implementation targets python programmer who is unfamiliar with the minidom module of python.
xmlsh.py code follows:
View xmlsh.pyHide xmlsh.py
""" A basic implementation of (xmllint --shell)
Author: Prasad.A
"""
import sys
from xml.dom import minidom
from readline import *
class xmlsh(object):
"""The base class which holds the xml document."""
def __init__(self,xmlfile):
self.filename=xmlfile
self.__loadFile()
def __loadFile(self):
self.xmlDoc = minidom.parse(self.filename)
# Get the element from the dom (currentElement)
def __getElement(self,elemname,currentElement,index=0):
if(elemname==""): return (currentElement,1)
elementList = currentElement.getElementsByTagName(elemname)
return (elementList[index],len(elementList))
# Handler for cat command
def __catHandler(self,path,currentElement):
if(path[0]=="/"): #absolute path is used
element=self.xmlDoc
path=path[1:]
else: # relative path is used
element=currentElement
parentElement = None
count=-1
pathSplit = path.split("/")
if(len(pathSplit)>1):
for elemname in pathSplit[:len(pathSplit)]:
parentElement = element
(element,count) = self.__getElement(elemname,element)
else:
(element,count) = self.__getElement(pathSplit[-1],element)
if(count != -1 and count > 1):
for index in range(count):
(element,count) = self.__getElement(pathSplit[-1],parentElement,index)
print element.toxml()
# Display the help
def __printHelp(self):
print """
The following commands are supported:
cd [xpath]: Change to the given node.
cat [xpath]: See the content.
pwd : Current position in the document.
help : Displays this help.
This implementation will support only very basic xpath.
"""
# Wrapper for displaying help
def help(self):
self.__printHelp()
# Main loop to run the program
def run(self):
print "Type bye or quit to terminate."
stop = False
prompt = "/"
self.currentElement = self.xmlDoc
while(stop!=True):
try:
# Accept the input
inputLine = raw_input("%s%s " % (prompt,">"))
# If the input is empty or newline do nothing
if(inputLine == "" or inputLine == "\n"): continue
# Split the input
inputSplit = inputLine.split()
# Assume the first element of split is command
command = inputSplit[0]
# Adjust the arguments passed
arguments=None
if(len(inputSplit) > 1): arguments = "".join(inputSplit[1:])
# Command is not still handled
commandHandled =False
# Handle "bye" or "quit" command
if(command=="bye" or command=="quit"):
commandHandled=True
stop=True
continue
# Handle "cd" command
if(command=="cd"):
commandHandled=True
inputArg=arguments
if(arguments[0]=="/"):
arguments=arguments[1:]
self.currentElement=self.xmlDoc
element=self.currentElement
parentElement=None
count = -1
pathSplit=arguments.split("/")
if(len(pathSplit) > 1):
for elemname in pathSplit[:len(pathSplit)-1]:
parentElement=element
(element,count)=self.__getElement(elemname,element)
parentElement=element
(element,count)=self.__getElement(pathSplit[-1],element)
whichOne=-1
if(count!=-1 and count>1):
print count, " elements of ", pathSplit[-1]," is present."
whichOne = raw_input("Specify the index to select: ")
if whichOne != " ":
whichOne = int(whichOne)
(element,count) = self.__getElement(pathSplit[-1],parentElement,whichOne-1)
else:
element=parentElement
self.currentElement=element
separator="/"
if(inputArg[0]=="/"):
prompt=""
separator=""
elif(prompt=="/"):
prompt=""
separator="/"
if(whichOne==-1): prompt="%s%s%s" % (prompt,separator,inputArg)
else: prompt="%s%s%s[%d]" % (prompt,separator,inputArg,whichOne)
if(self.currentElement==None):
stop=True
continue
# Handle "cat" command
if(command=="cat"):
commandHandled = True
if(arguments != None): self.__catHandler(arguments,self.currentElement)
else: print self.currentElement.toxml()
# Handle "pwd" command
if(command=="pwd"):
commandHandled = True
print prompt
# Handle "help" command
if(command=="help"):
commandHandled = True
self.__printHelp()
if(commandHandled==False):
print "Unknown Command:"
print self.__printHelp()
except Exception, ex:
print "Exception: ",ex
# Start the shell
if(len(sys.argv)>1):
ob=xmlsh(sys.argv[1])
print "Object created...function run() will be invoked..."
ob.help()
ob.run()
else:
print "Usage: python", sys.argv[0], "xmlfilename"
A small example follows that will explain the usage of this tool.
View UsageHide Usage
XML File: xmlsh.xml
<?xml version="1.0"?>
<root>
<element>
<item>
<title>Title of item1</title>
<description>Description of item1</description>
</item>
<item>
<title>Title of item2</title>
<description>Description of item2</description>
</item>
<item>
<title>Title of item3</title>
<description>Description of item3</description>
</item>
<item>
<title>Title of item4</title>
<description>Description of item4</description>
</item>
</element>
</root>
Usage: python xmlsh.py xmlsh.xml
/> cat
/> cd root
/root> cd /root/element
/root/element> cat
/root/element> cd item
[Specify the index: 1]
/root/element/item[1]> cat
/root/element/item[1]> cd /root/element
/root/element> pwd
/root/element> cd item
[Specify the index: 2]
/root/element/item[2]> cd /
/> bye