import cannot be used inside eval

Gary Herron gherron at
Thu Feb 4 03:55:50 EST 2016

On 02/03/2016 09:03 PM, 阎兆珣 wrote:
>     a = input("tell me which py to execute:  ")
>     print(a)
>     print('import '+a)
>     print(type('import'+a))
>     eval('print(a)')
Eval is meant to evaluate Python expressions.  The import is a 
statement, not an expression.  Also, it's a bad idea to use eval like 
this, and it's a *really* bad idea to use eval with user supplied 
input.  The user could inject *any* malicious code.

Instead, use the importlib module to programmatically import a module.

Gary Herron

Dr. Gary Herron
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418

More information about the Python-list mailing list