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"
理想情况下,解析的结果将是命令后跟可选参数。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
请参阅我在 Pyparsing wiki 讨论页面上回答此问题的示例形状解析语法: http:// /pyparsing.wikispaces.com/message/view/home/49369254。每个语法构造都映射到可以从解析的标记构造的类类型。完成后,您将有效地将输入文本反序列化为类实例列表,这些实例本身可以使用
execute
或__call__
方法定义来执行所需的任务。您可以在 pyparsing wiki 示例页面的 SimpleBool.py 示例中查看更多示例。另请参阅我在 PyCon '06 上展示的示例冒险游戏解析器,您可以在 http: //www.ptmcg.com/geo/python/index.html。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.要将字符串拆分为参数列表,类似于 Unix shell 的操作方式,您可以使用
shlex module
:
输出
每个列表中的第一项是命令,其余是选项:
To split a string into an argument list similar to how the Unix shell does it you could use
shlex
module:Output
The first item in each list is a command, the rest are options: