How to execute lists of code? Or alternatives.

rzantow at my-deja.com rzantow at my-deja.com
Tue May 9 14:55:26 EDT 2000


In article <etdbt2fakp8.fsf at w20-575-109.mit.edu>,
  Alex <cut_me_out at hotmail.com> wrote:
>
> You can probably do what you want with the exec command:
>
> >>> exec ('print "hi"')
> hi
> >>>
>
> You might want to check out the compile command, too.  It could speed
> things up a bit, if you are executing the same strings over and over:
>
> >>> print compile.__doc__
> compile(source, filename, mode) -> code object
>
> Compile the source string (a Python module, statement or expression)
> into a code object that can be executed by the exec statement or eval
().
> The filename will be used for run-time error messages.
> The mode must be 'exec' to compile a module, 'single' to compile a
> single (interactive) statement, or 'eval' to compile an expression.
> >>> c = compile ('print "hi"', 'string', 'single')
> >>> exec (c)
> hi
>
> Alex.
>

Alex (and others):

Thank you for your replies. I had tried using exec previously, but
perhaps incorrectly. Given a compound statement, I kept getting syntax
errors (passing one line at a time gives 'unexpected EOF while
parsing'; passing the list gives 'exec 1st arg must be string, code or
file object'; passing the joined list gives 'invalid syntax'). If there
is a way to exec multiple statements (including conditionals, loops,
etc.), that would be fine. I just don't know what that way is.

What I was really looking for, though, was the equivalent of exec_file
for an arbitrary list, as in:
   statement 1
   while condition:
      if condition:
         statement 2
 ... etc., so that I could read this group in from a file, store it and
later, when triggered, execute just this list of statements. As I said,
if it were kept in a separate file, exec_file would work just great,
but I would have potentially hundreds of these little things to manage.

Mr. Lundh's response to a related question looks interesting, though. I
may be able to make use of that. Thanks again to all.

--
Pythons, unlike some other snakes, do have hindlimbs, but they never
develop beyond vestigial stumps. The arrest of limb development is
due to a failure of the sonic hedgehog signalling system ...


Sent via Deja.com http://www.deja.com/
Before you buy.



More information about the Python-list mailing list