Re: eval( 'import math' )

2016-02-04 Thread Peter Otten
阎兆珣 wrote:

>Excuse me for the same problem in Python 3.4.2-32bit
> 
>I just discovered that  function does not necessarily take the
>string input and transfer it to a command to execute.
> 
>So is there a problem with my assumption?

Python discriminates between statements and expressions. The eval function 
will only accept an expression. OK:

>>> eval("1 + 1")
2
>>> eval("print(42)") # Python 3 only; in Python 2 print is a statement
42
>>> x = y = 1
>>> eval("x > y")
False

Not acceptable:

>>> eval("1+1; 2+2")
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 1
1+1; 2+2
   ^
SyntaxError: invalid syntax

>>> eval("import os")
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 1
import os
 ^
SyntaxError: invalid syntax

>>> eval("if x > y: print(42)")
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 1
if x > y: print(42)
 ^
SyntaxError: invalid syntax

To import a module dynamically either switch to exec()

>>> exec("import os")
>>> os


or use the import_module() function:

>>> import importlib
>>> eval("importlib.import_module('os')")


Of course you can use that function directly

>>> importlib.import_module("os")


and that's what you should do if your goal is to import a module rather than 
to run arbitrary Python code.

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: eval( 'import math' )

2016-02-04 Thread Ian Kelly
On Thu, Feb 4, 2016 at 6:33 AM, 阎兆珣  wrote:
>Excuse me for the same problem in Python 3.4.2-32bit
>
>I just discovered that  function does not necessarily take the
>string input and transfer it to a command to execute.
>
>So is there a problem with my assumption?

eval evaluates an expression, not a statement. For that, you would use exec.

If you're just trying to import though, then you don't need it at all.
Use the importlib.import_module function instead to import a module
determined at runtime. This is more secure than eval or exec, which
can cause any arbitrary Python code to be executed.
-- 
https://mail.python.org/mailman/listinfo/python-list


RE: eval( 'import math' )

2016-02-04 Thread Lutz Horn
Hi,

>I just discovered that  function does not necessarily take the
>string input and transfer it to a command to execute.

Can you please show us the code you try to execute and tells what result you 
expect?

Lutz

  
-- 
https://mail.python.org/mailman/listinfo/python-list