More like a shell command.

castironpi castironpi at gmail.com
Wed Aug 6 12:56:27 EDT 2008


On Aug 6, 9:38 am, Bill <galaxyblu... at gmail.com> wrote:
> Is there anyway I can extend python to accept a command
> which looks more like shell syntax than a function call.
>
> I want to be able to do this:
>
>     if blah :
>         MyCommand  Arg1  Arg2
>
> as opposed to this:
>
>     if blah :
>         MyCommand(Arg1,Arg2)
>
> or this:
>
>     if blah :
>         x("MyCommand  Arg1  Arg2")
>
> Of source, I would like to do this by writing a module (or through
> some other run-time hook) as opposed to editing the Python source
> code.
>
> Thanks in advance
> (unless you are just a Python nut who is flaming to tell me that I
> should not want this.  :-)  )
>
> Bill

Bill,

You'll need to decide on a grammar you want to use beforehand.  What
do you do with:

>>> if f 0 and g

?

Does it translate to:

if f( 0 ) and g( )

or

if f( 0 and g )

?  If every line starts with its one and only function, and the
parameters exhaust the rest of the line, and you don't allow nested
expressions, you can run a preprocessor, then call Python.  (Those
three conditions are limiting.)  Here's the steps for each line.

1. strip leading tabs
2. compile( line, '<none>', 'exec' ) to check for SyntaxError
3. if found:
3a. replace first space with '('
3b. replace remaining space with ','
3c. add trailing ')'
3d. replace leading tabs

Then just run:

python preprocessor.py -filename-
python -filename-.pppy

Have a look at code.py and codeop.py as well and the
InteractiveInterpreter class.



More information about the Python-list mailing list