Steve Reiss
Steve Reiss

Reputation: 9

Pyparsing implementing a simple script command

I need to implement a very simple grammar to parse a simple command language that would be read from a file. I would like to use PyParsing :

Example commands in input file :

## comment line - skip to next
CopyFile c:\temp\file1.txt  c:\temp\file2.txt
CreateDir "Junk"
MoveFile c:\temp\file1.txt  c:\temp\file2.txt
CreateFolder "Name"
DeleteFolder "Name"
FolderStruct "startNode"
FolderList "folderName" 

Ideally, the result of the parsing would be the command followed by the optional arguments.

Upvotes: 0

Views: 567

Answers (2)

jfs
jfs

Reputation: 414675

To split a string into an argument list similar to how the Unix shell does it you could use shlex module:

import fileinput
from shlex import shlex

def split(s):
    lex = shlex(s, posix=True)
    lex.escape = '' # treat all characters including backslash '\' literally
    lex.whitespace_split = True
    return list(lex)

for line in fileinput.input():
    args = split(line)
    if args:
       print(args)

Output

The first item in each list is a command, the rest are options:

['CopyFile', 'c:\\temp\\file1.txt', 'c:\\temp\\file2.txt']
['CreateDir', 'Junk']
['MoveFile', 'c:\\temp\\file1.txt', 'c:\\temp\\file2.txt']
['CreateFolder', 'Name']
['DeleteFolder', 'Name']
['FolderStruct', 'startNode']
['FolderList', 'folderName']

Upvotes: 2

PaulMcG
PaulMcG

Reputation: 63747

See my example Shape parsing grammar in response to this question on the Pyparsing wiki discussion page: http://pyparsing.wikispaces.com/message/view/home/49369254. Each grammar construct maps to a class type that can be constructed from the parsed tokens. When you are done, you will have effectively deserialized your input text into a list of class instances, which can themselves be defined with execute or __call__ methods to perform their desired task. You can see further examples of this in SimpleBool.py example from the pyparsing wiki Examples page. Also see the example adventure game parser I presented at PyCon '06, you can find links at http://www.ptmcg.com/geo/python/index.html.

Upvotes: 2

Related Questions