Questions tagged [python-exec]

For questions about exec/eval/etc and their behavior within Python

exec() function supports dynamic execution of Python code. object must be either a string or a code object. If it is a string, the string is parsed as a suite of Python statements which is then executed (unless a syntax error occurs).

If it is a code object, it is simply executed. In all cases, the code that’s executed is expected to be valid as file input (see the section “File input” in the Reference Manual). Be aware that the return and yield statements may not be used outside of function definitions even within the context of code passed to the exec() function. The return value is None.

Source

71 questions
46
votes
11 answers

Why should exec() and eval() be avoided?

I've seen this multiple times in multiple places, but never have found a satisfying explanation as to why this should be the case. So, hopefully, one will be presented here. Why should we (at least, generally) not use exec() and eval()? EDIT: I see…
Isaac
  • 15,783
  • 9
  • 53
  • 76
13
votes
3 answers

How to safely use exec() in Python?

I have been tasked with building an application where an end user can have custom rules to evaluate whether a returned query results in a warning or alert (based on there own thresholds). I've built a way for the user to template their logic. An…
Andy
  • 49,085
  • 60
  • 166
  • 233
13
votes
1 answer

Why does Python 3 exec() fail when specifying locals?

The following executes without an error in Python 3: code = """ import math def func(x): return math.sin(x) func(10) """ _globals = {} exec(code, _globals) But if I try to capture the local variable dict as well, it fails with a…
jakevdp
  • 77,104
  • 11
  • 125
  • 160
11
votes
4 answers

Import python module over the internet/multiple protocols or dynamically create module

Is it possible to import a Python module from over the internet using the http(s), ftp, smb or any other protocol? If so, how? If not, why? I guess it's about making Python use more the one protocol(reading the filesystem) and enabling it to use…
Bleeding Fingers
  • 6,993
  • 7
  • 46
  • 74
10
votes
3 answers

listcomp unable to access locals defined in code called by exec if nested in function

Are there any python gurus out there able to explain why this code doesn't work : def f(code_str): exec(code_str) code = """ g = 5 x = [g for i in range(5)] """ f(code) Error: Traceback (most recent call last): File "py_exec_test.py",…
levesque
  • 8,756
  • 10
  • 36
  • 44
6
votes
3 answers

assignment within exec in python

I am trying to build calculator using PyQt5 and I get string which I need to evaluate and assign it to a variable so that I can Pass that variable to widgets as an answer . So far I can evaluate the expression but can't assing it . How can I do that…
orayan
  • 165
  • 2
  • 9
5
votes
2 answers

Python: Is exec always bad practice and if so why not deprecated

Can someone think of an example with good practice that uses exec? If there is always a more efficient and secure way to replace exec, why python doesn't deprecate exec?
zvisofer
  • 1,346
  • 18
  • 41
4
votes
2 answers

Closure lost during callback defined in exec()

It's my third day using Python, so forgive newbie mistakes. So here's my working code. person.test() registers a callback with the boss, the boss calls the callback, everything works fine. class Boss: def registerCallback(self,cb): self.cb =…
JeramieH
  • 129
  • 9
4
votes
2 answers

Why is a Python generator confusing its scope with global in an exec'd script?

Ok, so I'm working in an environment where a config script for a tool is an exec'd python script. The exec call is something like this: outer.py: exec(open("inner.py").read(), globals(), {}) Now, I want to do some relatively basic iteration within…
Nevir
  • 7,951
  • 4
  • 41
  • 50
3
votes
2 answers

Python exec with a function chain producing NameError

Consider the following script, which uses exec to define two functions, one of which calls the other: def run_code(): code = """ def foo(): print('foo') return 1 def bar(): print('bar calls foo') return 1 + foo() result = bar() """ …
k_ssb
  • 6,024
  • 23
  • 47
3
votes
1 answer

Programmatically execute a Python file from within Python in a fresh-looking Python environment

Let's say I have a file script.py located at path = "foo/bar/script.py". I'm looking for a way in Python to programmatically execute script.py from within my main Python program through a function execute_script(). However, I've got a few…
balu
  • 3,500
  • 4
  • 34
  • 35
3
votes
1 answer

exec function not working properly in python 3.6

Code I wrote tile1=0; player1=1; turn=player1 def s(): global tile1,turn,player1 print("Before",tile1) string='tile' + '1' # I am getting 1 by some function that's why I need to create variable string …
A Q
  • 166
  • 2
  • 13
3
votes
1 answer

Importing code from a dynamically created module in Python

I have a project that tries to create a new module dynamically and then in a subsequent exec statement tries to import that module. import imp s=""" class MyClass(object): def __init__(self): pass def foo(self): …
mottosan
  • 466
  • 3
  • 14
3
votes
2 answers

python3 print() in exec()

In python3, when I run >>> exec("","","") TypeError: exec() arg 2 must be a dict, not str >>> exec( "print('Hello')", print("World"), print("!") ) World ! Hello >>> type(print("World")) World I mean in the Python3, the arg2 of…
user447586
  • 281
  • 2
  • 11
2
votes
1 answer

Why do I get "NameError: name is not defined" with exec()?

When I try this code in a console (in PyCharm): exec("import random") exec("def f():\n\treturn random.randint(0, 10), random.randint(0, 10)") locals()['f']() it works fine. But when I try to do exactly the same in my program it doesn't work, and I…
kostbash
  • 206
  • 3
  • 7
1
2 3 4 5