Pyparsing 实现简单脚本命令
我需要实现一个非常简单的语法,用来解析一种简单的命令语言,这些命令会从一个文件中读取。我想使用PyParsing这个工具。
输入文件中的命令示例:
## 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"
理想情况下,解析的结果应该是命令后面跟着可选的参数。
2 个回答
2
你可以查看我在Pyparsing的讨论页面上针对这个问题提供的形状解析语法示例:http://pyparsing.wikispaces.com/message/view/home/49369254。每个语法结构都对应一个可以从解析的标记中构建的类类型。当你完成后,你实际上就是把输入的文本转化成了一系列的类实例,这些实例可以用execute
或__call__
方法来执行它们想要完成的任务。你可以在pyparsing的示例页面上找到更多类似的例子,比如SimpleBool.py。此外,我在2006年的PyCon上展示的冒险游戏解析器的例子也很有趣,你可以在这里找到相关链接:http://www.ptmcg.com/geo/python/index.html。
2
如果你想把一个字符串分割成类似于Unix命令行那样的参数列表,可以使用shlex
模块。
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)
输出结果
每个列表中的第一个项目是一个命令,后面的都是选项:
['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']