Author Options:

Command parsing in Python? Answered

I am currently attempting an Interactive Fiction game in Python (when I am finished I plan to write an instructable detailing how I did it). The only problem I have run into is the parser. I want to be able to specify a syntax for a command, and have the parser be able to recognize when the command is being input regardless of the arguments passed to it, as well as be able to extract the arguments from the inputted command. This would not be so much of a problem if there were not both one-argument and two-argument commands, and the fact that "throw x to y" is a different command than, say, "throw x aty".

Any help would be greatly appreciated.


I am working on something similar in python. I have been searching for a good interactive parser but have not really found anything suitable.

The conclusion i have drawn is to use a proper parser (such as yapp or simpleparse) or write it from scratch with the re module. Annoyingly either solution means sidetracking from the goals, and i am leaning towards re because using a parser will probably be overkill.

There is the cmd module but it is quite limited and not great for dynamic commands and contexts, but if you want something to get you up and running it may be a safe bet.

There have been a number of books on writing such games; I'd suggest hitting a library and getting your paws on one of those. It probably won't be in Python, but the principles are the same no matter what language you're working in: define the grammar for your command language, implement the lexer, implement the parser, insert slot A very fine and around tabbing 12.