eval( 'import math' )
Peter Otten
__peter__ at web.de
Thu Feb 4 09:48:31 EST 2016
阎兆珣 wrote:
> Excuse me for the same problem in Python 3.4.2-32bit
>
> I just discovered that <eval()> 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 "<stdin>", line 1, in <module>
File "<string>", line 1
1+1; 2+2
^
SyntaxError: invalid syntax
>>> eval("import os")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1
import os
^
SyntaxError: invalid syntax
>>> eval("if x > y: print(42)")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1
if x > y: print(42)
^
SyntaxError: invalid syntax
To import a module dynamically either switch to exec()
>>> exec("import os")
>>> os
<module 'os' from '/usr/lib/python3.4/os.py'>
or use the import_module() function:
>>> import importlib
>>> eval("importlib.import_module('os')")
<module 'os' from '/usr/lib/python3.4/os.py'>
Of course you can use that function directly
>>> importlib.import_module("os")
<module 'os' from '/usr/lib/python3.4/os.py'>
and that's what you should do if your goal is to import a module rather than
to run arbitrary Python code.
More information about the Python-list
mailing list