•
Re: from <module> import * ET __import__
Posté par
ychaouche
le
04/06/2008 10:35
Je veux importer dynamiquement le fichier testArgs.py dont voici le code :
def spam(*args,**kw):
for arg in args:
print "argument : ",arg
egg(*args,**kw)
def egg(a,b=19,c=2):
whatevers = 302198
#print "a",a,"b",b,"c",c
print dir(egg.func_code)
print egg.func_code.co_varnames
print egg.func_code.co_stacksize
bacon(whatevers)
def bacon(a):
print a
kw = {'a':"2",'c':'21'}
spam(**kw)
Voici la trace de mon interprète python :
chaouche@bughunter:~/TEST/PYTHON$ python
Python 2.5.1 (r251:54863, Mar 7 2008, 04:10:12)
on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import imp
>>> imp.find_module("testArgs"
(<open file 'testArgs.py', mode 'U' at 0xb7d4b800>, 'testArgs.py', ('.py', 'U', 1))
>>> o = imp.find_module("testArgs"
>>> m = imp.load_module("testArgs.py",*o)
['__class__', '__cmp__', '__delattr__', '__doc__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'co_argcount', 'co_cellvars', 'co_code', 'co_consts', 'co_filename', 'co_firstlineno', 'co_flags', 'co_freevars', 'co_lnotab', 'co_name', 'co_names', 'co_nlocals', 'co_stacksize', 'co_varnames']
('a', 'b', 'c', 'whatevers')
2
302198
>>> m
<module 'testArgs.py' from 'testArgs.pyc'>
>>> from pprint import pprint
>>> pprint(dir(m))
['__builtins__',
'__doc__',
'__file__',
'__name__',
'bacon',
'egg',
'kw',
'spam']
>>>
Comme on peut le voir, le nom des fonctions est bien présent dans le module, ainsi que les variables globales (kw). On peut donc importer ce qu'on veut.
|