How about this:
def test():
exec (code, globals())
f()
Answer from Yevgen Yampolskiy on Stack OverflowHow about this:
def test():
exec (code, globals())
f()
What's going on here is that the module random is being imported as a local variable in test. Try this
def test():
exec code
print globals()
print locals()
f()
will print
{'code': '\nimport random\ndef f():\n print random.randint(0,9)\n', '__builtins__': <module '__builtin__' (built-in)>, '__package__': None, 'test': <function test at 0x02958BF0>, '__name__': '__main__', '__doc__': None}
{'random': <module 'random' from 'C:\Python27\lib\random.pyc'>, 'f': <function f at 0x0295A070>}
The reason f can't see random is that f is not a nested function inside of test--if you did this:
def test():
import random
def f():
print random.randint(0,9)
f()
it would work. However, nested functions require that the outer function contains the definition of the inner function when the outer function is compiled--this is because you need to set up cell variables to hold variables that are shared between the two (outer and inner) functions.
To get random into the global namespace, you would just do something like this
exec code in globals(),globals()
The arguments to exec after the in keyword are the global and local namespaces in which the code is executed (and thus, where name's defined in the exec'd code are stored).
Import vs exec functions for using modules
django - Python: 'import *' vs execfile - Stack Overflow
How to make modules from exec("import xxx") in a Python function available? - Stack Overflow
exec statement python and importing module - Stack Overflow
Videos
Hi guys, I am currently reading learning python by O'Reilly and they were discussing different ways of importing modules. I am new so please correct my terminology. I was wondering what the difference is between import module, from module import x and exec.
Import Module allows me to import the module but requires the function reload if my_module were to be edited. This also has its own namespace. E.g module.function
From module import function, is like import but it overrides variables.
Exec in python 3 uses the current version of the module if any changes were made.
So is this the reasons why we would want to use each one.
Import module - pros own namespace. Cons import all function, has to reload
From module import function - pros can choose function, cons overrides variables, has to reload
Exec - pros uses latest changes to file(does not need reload) cons overrides variables
Sorry if format is bad, Doing this on my phone , will edit later
Would this be an appropriate stack overflow question?
edit:Got this from stack overflow, now trying to figure out when exec is used instead
After import x, you can refer to things in x like x.something. After from x import *, you can refer to things in x directly just as something. Because the second form imports the names directly into the local namespace, it creates the potential for conflicts if you import things from many modules. Therefore, the from x import * is discouraged.
Using execfile function will result in the evaluation of the Python source file (.py) every time the settings file is evaluated. You are executing the Python parser each time. Using import wouldn't necessarily do this (might use the .pyc file). Generally the first time you run a project in Python (at least, cPython) it gets compiled to bytecode and not recompiled again. You are breaking that. This isn't necessarily a problem, but you should be aware of it.
Using execfile will also result in all of the imports you may have in the settings_local.py file being re-evaluated in the module scope of the settings.py file. Using import * would have included all items in the settings_local.py module scope. The net effect is the same (all items included in settings_local.py module scope are included in settings.py) but the method is different.
Finally, it's normal for modules to be executed as modules rather than included. It is reasonable for code to include things such as os.path.dirname(__file__). If any code did use this, you would confuse it as the code would no longer be executing in the module that the author might reasonably have expected.
In my experience, people use import not execfile. Django is very much 'convention over configuration'. Follow the convention.
Another difference: execfile gets a context dictionary; the global context by default or a specified dictionary. This could allow some strange things
dont_do_this.py:
# Probably not a good thing to do
z=x+1 # an expression that involves an un-defined field
Obviously,
from dont_do_this import *
fails.
However,
d={'x':1}
execfile( 'dont_do_this.py', d )
is OK and results in d=={'x':1, 'z':2}
Note that
x=1
execfile( 'dont_do_this.py' )
is OK and results in the variable z being added to the globals.
exec executes code in the current scope. Inside a function, this means the (function-) local scope.
You can tell exec to put variables in another scope by giving it a tuple (code, scope). For example, you can use globals() to make names available at the module level.
Be aware, that globals
is always the dictionary of the current module (inside a function or method, this is the module where it is defined, not the module from which it is called).
Thus, in your example, you have to pass the desired scope to your utility function:
anyimport.py:
class anyimport(object):
def __init__(self, importmodule, scope):
exec (importmodule, scope)
test.py:
a = 42
b = 'foo'
main.py:
from anyimport import anyimport
if __name__ == '__main__':
anyimport('from test import *', globals())
# 42 foo
print a, b
Test it with python main.py. Make sure all files are present in the current directory.
Alternative Solution
If you are not bound to use exec, a more elegant way would be to use the import utilities provided by Python.
The following, taken from https://stackoverflow.com/a/4526709/453074 , is equivalent to from some.package import *:
[...] it's more convenient to user
importlib:
globals().update(importlib.import_module('some.package').__dict__)
.
You might want to try something like this:
_globals = {}
code = """import math;"""
code += """import numpy;"""
code = compile(code, '<string>', 'exec')
exec code in _globals
It's safer than just doing an exec, and it should import correctly inside a function's local scope.
You can then update globals() with whatever modules (or functions) you import.
When using exec for functions, you can get a handle to globals with g = globals(), then do an update on g. For modules, you should do another step... you will want to also update the modules in sys.modules as well.
UPDATE: to be explicit:
>>> def foo(import_string):
... _globals = {}
... code = compile(import_string, '<string>', 'exec')
... exec code in _globals
... import sys
... g = globals()
... g.update(_globals)
... sys.modules.update(_globals)
...
>>> foo('import numpy as np')
>>> np.linspace
<function linspace at 0x1009fc848>
You probably mean execfile(jobname). And import does not work with filenames. It works with package names. Any good tutorial would cover that. Another issue would be the \t being interpreted as a tab character, but here it is not the case because you are uaing forward slash not baclslash...
Somehow, I think you must be calling
test('c:\python27\test1.py')
instead of
test('c:/python27/test1.py')
The backslash in front of the t is being interpreted as a tab character. Thus the error
import:c:\python27 est1.py
Notice the missing t.
Secondly, the import command expects a module name, not a path. For importing, use __import__ not exec or execfile. execfile has been removed from Python3, so for future compatibilty, you may not want to use it in Python2. exec can be used instead, but there are problems with using exec.
Assuming c:\python27 is in your PYTHONPATH, you could
do something like this:
def test(jobname):
print jobname
__import__(jobname)
if __name__ == '__main__':
test('test1')
According to the Python documentation, instead of this:
execfile("./filename")
Use this:
exec(open("./filename").read())
See Python's docs for:
- What’s New In Python 3.0
execfileexec
You are just supposed to read the file and exec the code yourself. 2to3 currently replaces this:
execfile("somefile.py", global_vars, local_vars)
With this:
with open("somefile.py") as f:
code = compile(f.read(), "somefile.py", 'exec')
exec(code, global_vars, local_vars)
(The compile call isn't strictly needed, but it associates the filename with the code object, making debugging a little easier).
See Python's docs for:
execfilecompileexec
The problem is you're importing "module" instead of the specified module, and you didn't put the name module anywhere. A stupid fix to this would be to always using exec
def get_doc(module):
exec "import {}".format(module)
exec "print {}.__doc__".format(module)"
But instead of exec, i would advise you to use the __import__ function:
def get_doc(module):
module = __import__(module)
print module.__doc__
Which allows more flexibility, and you can modify, use module as you wanted.
When you say
get_doc(sys)
python will not be able to recognize sys. The actual way to do what you are trying to do would be to
pass the module name as a string parameter
use
__import__function to load the module, like thisdef get_doc(module): mod = __import__(module) print mod.__doc__ get_doc("sys")
Note: I am not in favor of executing dynamic code in programs, but if you must use exec to solve this problem read this and have a basic understanding about the security implications and then look at aIKid's solution.