How To Call A Function Stored In Another File From A Python Program?
Solution 1:
You are looking for the exec keyword.
>>>mycode = 'print "hello world"'>>>exec mycode
Hello world
So if you read your text file as text (assuming that it only contains the function) like:
test.txt:
defa():
print"a()"
test.py:
mycode = open('test.txt').read()
exec mycode # this will execute the code in your textfile, thus define the a() function
a() # now you can call the function from your python file
Link to doc: http://docs.python.org/reference/simple_stmts.html#grammar-token-exec%5Fstmt
You may want to look at the compile statement too: here.
Solution 2:
compile() and eval() can do the trick:
>>>code = compile('def foo(a): return a*2', '<string>', 'exec')>>>eval(code)>>>foo
52: <function foo at 0x01F65F70>
>>>foo(12)
53: 24
or with file:
withopen(filename) as source:
eval(compile(source.read(), filename, 'exec'))
Solution 3:
A way like Reflection in Java? If so, Python has a module named imp to provide it.
foo.py
def foo():
return "returnfrom function foo in file foo.py"
some code anywhere
modes = imp.get_suffixes() #got modes Explained in link below
mode = modes[-2] # because I want load a py filewithopen("foo.py") as file:
m = imp.load_module("name", file, "foo.py", mode)
print(m.foo())
above mode = modes[-2]
because my imp.get_suffixes()
is:
>>> imp.get_suffixes()
[('.cpython-32m.so', 'rb', 3), ('module.cpython-32m.so', 'rb', 3), ('.abi3.so', 'rb', 3), ('module.abi3.so', 'rb', 3), ('.so', 'rb', 3), ('module.so', 'rb', 3), ('.py', 'U', 1), ('.pyc', 'rb', 2)]
here is my output:
Python 3.2.1 (default, Aug 112011, 01:27:29)
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
Type"help", "copyright", "credits"or"license"for more information.
>>> import imp
>>> withopen("foo.py") as file:
... m = imp.load_module("foo", file, "foo.py", ('.py', 'U', 1))
... >>> m.foo()
'return from function foo in file foo.py'
Check it here: http://docs.python.org/py3k/library/imp.html Both python 2.7 and python 3 works:
Python 2.7.1 (r271:86832, Jun 162011, 16:59:05)
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
Type"help", "copyright", "credits"or"license"for more information.
>>> import imp
>>> imp.get_suffixes()
[('.so', 'rb', 3), ('module.so', 'rb', 3), ('.py', 'U', 1), ('.pyc', 'rb', 2)]
>>> withopen("foo.py") as file:
... m = imp.load_module("foo", file, "foo.py", ('.py', 'U', 1))
... >>> m.foo()
'return from function foo in file foo.py'
Solution 4:
You can use execfile:
execfile("path/example.py")
# example.py# def example_func():# return "Test"#print example_func()
# >Test
EDIT:
In case you want to execute some unsecure code, you can try to sandbox it this way, although it is probably not very safe anyway:
defexecfile_sandbox(filename):
from copy import copy
loc = globals()
bi = loc["__builtins__"]
ifnotisinstance(bi, dict): bi = bi.__dict__
bi = copy(bi)
# no filesdel bi["file"]
# and definitely, no importdel bi["__import__"]
# you can delete other builtin functions you want to deny access to
new_locals = dict()
new_locals["__builtins__"] = bi
execfile(filename, new_locals, new_locals)
Usage:
try:
execfile_sandbox("path/example.py")
except:
# handle exception and errors here (like import error)pass
Solution 5:
I am not sure what is your purpose, but I suppose that you have function in one program and you do want that function run in another program. You can "marshal" function from first to second.
Example, first program:
# first programdefyour_func():
return"your function"import marshal
marshal.dump(your_func.func_code, file("path/function.bin","w"))
Second program:
# Second programimport marshal, types
code = marshal.load(file("path/function.bin"))
your_func = types.FunctionType(code, globals(), "your_func")
print your_func()
# >your function
Post a Comment for "How To Call A Function Stored In Another File From A Python Program?"