[python-win32] How Can I exec() a statement?

Steve Holden steve at holdenweb.com
Wed Apr 6 20:55:10 CEST 2005


* William wrote:
> Hello all.
>  
> Thanks for the tips and solutions posted to the list so far.  This is a 
> general python question, not windows specific.  It is my turn to ask. 
> (Perhaps the notion below will suggest some development to one of you. 
> Who knows?)
>  
> I want to execute a statement indirectly in Python. Take the simple case 
> below.  The chevrons ">> " indicate the result of the statement
> 
>     b = 2
>     a = b + 6
>     eval('a = b + 6', globals(), locals() )
>      >>   File "not_much_at_all.py", line 21, in ?
>      >>       rslt = eval('a = b + 6', globals(), locals() )
>      >>   File "<string>", line 1
>      >>     a = b + 6
>      >>       ^
>      >> SyntaxError: invalid syntax
> 
> While I appreciate that "eval()" is not the way to do this, it is also 
> true that "eval()" accurately signals my intention in this sample.
>  
> HOW -- or, is it possible -- to execute the an assignment statement from 
> a string?
>  
> I have used compile() and considered using a 'block'.  Compile doesn't 
> help.  And I can't find an equivalent for 'eval( <block> )' ...
>  
> Who has the answer?
>  
Well, you do! You ask how to exec a statement, and the answer is ... use 
an "exec" statement!

  >>> exec "a = 25/3"
  >>> a
8
  >>>

regards
  Steve
-- 
Steve Holden        +1 703 861 4237  +1 800 494 3119
Holden Web LLC             http://www.holdenweb.com/
Python Web Programming  http://pydish.holdenweb.com/


More information about the Python-win32 mailing list