Loading functions from a file during run-time

Grant Edwards grante at visi.com
Thu Feb 10 23:31:27 EST 2005


On 2005-02-11, Bryant Huang <735115 at gmail.com> wrote:

> I would like to read in files, during run-time, which contain
> plain Python function definitions, and then call those
> functions by their string name. In other words, I'd like to
> read in arbitrary files with function definitions, using a
> typical 'open()' call, but then have those functions available
> for use.

that's pretty simple:

  $ cat foo.txt
  def foo():
      print "foo here"
  def bar():
      print "bar here"
      
  $ cat foo.py
  filename = 'foo.txt'
  execfile(filename)
  foo()
  bar()
  
  $ python foo.py
  foo here
  bar here

> The 'import' keyword is not appropriate, AFAIK, because I want to be
> able to open any file, not one that I know ahead of time (and thus can
> import at design-time).

This will import a module name determined at run-time:

  exec('import %s' % moduleName)

> The following is a toy example of what I'm doing so far.

[...]

> I'm not sure exactly what happens below the surface, but I'm
> guessing the 'compile()' and 'exec()' commands load in
> 'negate()' and 'square()' as functions in the global scope of
> 'foo.py'. I find that when I run 'compile()' and 'exec()' from
> within a function, say 'f()', the functions I read in from
> 'bar.txt' are no longer accessible since they are in global
> scope, and not in the scope of 'f()'.

Huh?  I'm lost.  What, exactly, are you trying to accomplish?

Did your example program do what you intended or not?

Is this what you're trying to do?

  $ cat foo.txt
  def foo():
      print "foo here"
  def bar():
      print "bar here"
  
  $ cat bar.py
  def testing():
      filename = 'foo.txt'
      execfile(filename,globals())
      foo()
      bar()
  testing()    
  foo()    
  bar()
  
  $ python bar.py
  foo here
  bar here
  foo here
  bar here

-- 
Grant Edwards                   grante             Yow!  Clear the
                                  at               laundromat!! This
                               visi.com            whirl-o-matic just had a
                                                   nuclear meltdown!!



More information about the Python-list mailing list