Python eval with import

Функция eval() в Python

Функция eval() в Python используется для синтаксического анализа строки выражения, как выражения Python и последующего ее выполнения.

eval(expression, globals=None, locals=None)

expression – обязательный строковый параметр, он анализируется и выполняется, как выражение Python.

globals – словарь, используемый для определения доступных для выполнения выражений. Стандартные встроенные методы доступны, если явно не ограничены с помощью элемента ‘__builtins__’: None.

locals – используется для указания локальных переменных и методов, доступных для функции eval().

Пример

Давайте сначала рассмотрим простой пример функции eval() в python.

x = 1 print(eval('x==1')) print(eval('x+2'))

eval() с пользовательским вводом

Приведенный выше пример функции eval() очень ограничен и не оправдывает ее возможности. Сила функции заключается в динамическом выполнении операторов. Мы можем выполнять произвольные объекты кода с помощью функции eval().

Давайте посмотрим на более сложный пример, где мы попросим пользователя ввести функции для выполнения.

# eval() with user input from math import * for l in range(1, 3): func = input("Enter Math Function to Evaluate:\n") try: print(eval(func)) except Exception as ex: print(ex) break print('Done')

На изображении ниже показан пример выполнения указанного выше скрипта Python.

Функция eval в python

Без функции eval мы не можем выполнять команды, введенные пользователем. В этом сила функции eval().

Риски безопасности

Что делать, если у нас есть импортированный модуль os и пользователь вводит команду os.system (‘rm -rf /’) для выполнения. Это приведет к удалению системных файлов и повреждению нашей среды.

Вот почему, когда вы используете функцию eval() для выполнения кода ввода пользователя, вам необходимо убедиться, что введенные пользователем данные сначала проверяются, и если они в порядке, то выполняется только их. Вот тогда и пригодятся параметры globals и locals.

Глобальные и локальные переменные

Прежде чем мы решим, какие функции мы должны сделать доступными для eval(), нам нужно выяснить, какие все функции и переменные присутствуют в глобальной и локальной области. Мы можем найти эту информацию с помощью встроенных функций locals(), globals() и dir().

Давайте посмотрим на пример, где мы узнаем функции и переменные, доступные в глобальной и локальной области.

from math import * def square_root(n): return sqrt(n) print(globals()) # dictionary representing the current global symbol table. print(locals()) # dictionary representing the current local symbol table. print(dir()) # list of names in the current local scope
, '__spec__': None, '__annotations__': <>, '__builtins__': , '__file__': '/Users/pankaj/Documents/PycharmProjects/BasicPython/basic_examples/eval_example.py', '__cached__': None, 'acos': , 'acosh': , 'asin': , 'asinh': , 'atan': , 'atan2': , 'atanh': , 'ceil': , 'copysign': , 'cos': , 'cosh': , 'degrees': , 'erf': , 'erfc': , 'exp': , 'expm1': , 'fabs': , 'factorial': , 'floor': , 'fmod': , 'frexp': , 'fsum': , 'gamma': , 'gcd': , 'hypot': , 'isclose': , 'isfinite': , 'isinf': , 'isnan': , 'ldexp': , 'lgamma': , 'log': , 'log1p': , 'log10': , 'log2': , 'modf': , 'pow': , 'radians': , 'remainder': , 'sin': , 'sinh': , 'sqrt': , 'tan': , 'tanh': , 'trunc': , 'pi': 3.141592653589793, 'e': 2.718281828459045, 'tau': 6.283185307179586, 'inf': inf, 'nan': nan, 'square_root': > , '__spec__': None, '__annotations__': <>, '__builtins__': , '__file__': '/Users/pankaj/Documents/PycharmProjects/BasicPython/basic_examples/eval_example.py', '__cached__': None, 'acos': , 'acosh': , 'asin': , 'asinh': , 'atan': , 'atan2': , 'atanh': , 'ceil': , 'copysign': , 'cos': , 'cosh': , 'degrees': , 'erf': , 'erfc': , 'exp': , 'expm1': , 'fabs': , 'factorial': , 'floor': , 'fmod': , 'frexp': , 'fsum': , 'gamma': , 'gcd': , 'hypot': , 'isclose': , 'isfinite': , 'isinf': , 'isnan': , 'ldexp': , 'lgamma': , 'log': , 'log1p': , 'log10': , 'log2': , 'modf': , 'pow': , 'radians': , 'remainder': , 'sin': , 'sinh': , 'sqrt': , 'tan': , 'tanh': , 'trunc': , 'pi': 3.141592653589793, 'e': 2.718281828459045, 'tau': 6.283185307179586, 'inf': inf, 'nan': nan, 'square_root': > ['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'square_root', 'tan', 'tanh', 'tau', 'trunc']

Это множество функций, к которым у eval() будет доступ. Большинство из них взяты из модуля __builtins__ и math.

Посмотрим, что произойдет, если мы укажем значение globals, как пустой словарь в функции eval.

Таким образом, для функции eval по-прежнему доступны встроенные методы. Если вы хотите ограничить доступ только к нескольким встроенным методам, вы можете указать его значение для глобальных переменных. Например, приведенный ниже код позволяет функции eval() выполнять только встроенную функцию min.

Давайте посмотрим на другой пример, где я предоставляю значение locals и отключаю доступ ко всем встроенным функциям для eval().

Давайте посмотрим на последний пример, в котором я разрешаю доступ только к некоторым методам из математического модуля. Мы также сопоставляем square_root с функцией sqrt для удобства чтения человеком.

from math import * for l in range(1, 3): func = input("Enter Math Function to Evaluate.\nAllowed Functions are: square_root(x) and pow(x,y):\n") try: print(eval(func, )) except Exception as ex: print(ex) break print('Done')
Enter Math Function to Evaluate. Allowed Functions are: square_root(x) and pow(x,y): square_root(16) 4.0 Enter Math Function to Evaluate. Allowed Functions are: square_root(x) and pow(x,y): log10(100) name 'log10' is not defined Done

Пример глобальных переменны в Python

Я ничего не указал для встроенных функций, поэтому они будут доступны для функции eval().

Ниже приведен еще один пример выполнения, показывающий, что встроенные функции доступны для выполнения.

Enter Math Function to Evaluate. Allowed Functions are: square_root(x) and pow(x,y): min(5,4) 4 Enter Math Function to Evaluate. Allowed Functions are: square_root(x) and pow(x,y): max(10,20) 20

Источник

eval to import a module

eval works only on expressions, import is a statement.

exec is a function in Python 3 : exec(‘import vfs_tests as v’)

To import a module using a string you should use importlib module:

import importlib mod = importlib.import_module('vfs_tests') 

In Python 2.6 and earlier use __import__ .

Ashwini Chaudhary 236361

My little trick if you want to pass all the code as string to eval function:

>>> eval('exec("import uuid") or str(uuid.uuid4())') 'bc4b921a-98da-447d-be91-8fc1cebc2f90' >>> eval('exec("import math") or math.sqrt(2)') 1.4142135623730951 

Actually. if you absolutely need to import using eval (for example, code injection), you can do it as follow in Python 3, since exec is a function:

eval("exec('import whatever_you_want')") 

enter image description here

  • import java ImportError: No module named java
  • Fabric cannot import module in function
  • import local python module in HTCondor
  • jenkins python module import error
  • Cannot import my own module when running script in Spyder
  • python cannot import module
  • Import Error — Tornado requires an updated SSL module on ubuntu 14.04
  • Is there a point to import the same module in two different ways in a program?
  • Python requests module import error
  • Import non-standard python module in Jython
  • Failed to import module when building the sphinx documentation
  • Cannot Import easygui module
  • Python : How to import a module if I have its path as a string?
  • Error while import tensorflow module
  • Import Error: No module named requests
  • Unique import * only allowed at module level
  • librosa module import in python3 throws warning
  • ImportError: No module named Window but from import works
  • Module Import Error when executing a Lambda python function
  • Can’t import module ANTLR MyGrammarLexer and MyGrammarParser
  • Python 3.4 — Cannot import module
  • python module import issues in command prompt
  • Import a module, from inside another module
  • How to import a class from a module from a package dynamically?
  • ImportError: cannot import name ‘dcc’ from partially initialized module ‘dash’ — python
  • from google.cloud import bigquery ModuleNotFoundError: No module named ‘google’
  • Cannot import Decimal module
  • Import dict without name from a module
  • Unable to import MySQLdb in ansible module
  • Is it possible to import a Python module (.py file) into a dict?
  • Why is python’s sqlite3 module trying to import datetime from my project directory?
  • How to import a file with delimiters irregular with the csv module in python?
  • How can I import a module into main() from a sub function?
  • boost.python code on module import
  • stumped by WSGI module import errors
  • import statement fails for one module
  • Get the import name of a module
  • Failed to import python module from different directory
  • python import a module with source code in temporary file
  • Python import functions from module twice with different internal imports
  • In general, is it a bad practice to use the statement «from module import *» in my python code?
  • Python import module works in prompt, but not in script
  • Beginner Python Import Module
  • py2exe cannot import Module from other directory
  • In interactive Python, how to unambiguously import a module
  • Import module with virtual environment in Python
  • Can you use Python relative imports to import the __init__ file of the current module under a specific name?
  • Import a module function from another folder in my module in python
  • Manage Python module dependency through a clever import
  • No module named combo (from import wx.combo) — pyspread

More Query from same tag

  • Making simple chatbot with pyqt5 without pushbutton
  • Google oAuth2 python application not opening login page online
  • Python Kafka consumer not reading messages as they arrive
  • Python modify value in list of dicts
  • MITMProxy: smart URL replacement
  • the right expression for [«A» for x in range(0,10) or «B» if x == 9] in python?
  • Parsing json into Insert statements with Python
  • I want to select some random numbers but their addition should always be even in Python
  • CVXPY expression doesn’t give expected result
  • How to make QRadioButton clickable area the whole button instead of just on the text
  • How to extract from a Python list while also accounting for the position of the extracted elements?
  • Finding words from random input letters in python. What algorithm to use/code already there?
  • Issue with ‘google.cloud.storage’. module has no attribute ‘Client’
  • Python Dictionary : Prevent previous value not overwritten by the new value
  • update dict using nested for loop
  • What’s the real signature of urllib2.urlopen
  • writing files, reading them and call them with different moduls
  • how to write a list of dictionaries into a CSV with multiple values
  • ‘Booster’ object has no attribute ‘score’ — Accuracy
  • Creating lists out of multiple duplicate strings in pandas dataframe
  • Python create folder for each file in a directory
  • sklearn.utils.class_weight throws «classes should include all valid labels that can be in y» error
  • Why do treeview widget put an extra column although I only gave it two? I also can’t control the width of it
  • How to read multiple nltk corpus files and write in a single text file in python
  • AttributeError: ‘Corn’ object has no attribute ‘_Plant__symbol’
  • change string on the fly in for loop
  • GNU Parallel to replace piping xargs -n 1
  • Is there a Python function for this piece of code?
  • Pwinauto: How to start an application without GUI error
  • Python SQLite: Update Statement TypeError: function takes exactly 2 arguments (1 given)
  • Python web scraping, getting a FileNotFound error
  • Matplotlib table falls outside plot area
  • Python list comprehension nested loop
  • Running function in IOLoop.current().run_in_executor?
  • python — modify a list of strings via regex

Источник

Читайте также:  Чем and отличается от python
Оцените статью