473,756 Members | 1,842 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Loading functions from a file during run-time

Hello!

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.

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).

I already have some code that I cobbled together from many newsgroup
posts, but I wonder if there's a cleaner/simpler way to do it.

The following is a toy example of what I'm doing so far. I have a file
called 'bar.txt' that contains two function definitions. I have a main
driver program called 'foo.py' which reads in 'bar.txt' (but should be
able to read any file it hasn't seen before), then calls the two
functions specified in 'bar.txt'.

===== [bar.txt] =====

def negate(x):
return -x

def square(x):
return x*x
===== [foo.py] =====

# open functions file
foo_file = open("bar.txt")
foo_lines = foo_file.readli nes()
foo_file.close( )
foo_str = "".join(foo_lin es)

# compile code
foo_code = compile(foo_str , "<string>", "exec")
foo_ns = {}
exec(foo_code) in foo_ns

# use functions
k = 5
print foo_ns["negate"](k) // outputs -5
print foo_ns["square"](k) // outputs 25
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()'.

Any pointers would be very welcome.

Thanks!
Bryant

Jul 18 '05 #1
11 1972
On 2005-02-11, Bryant Huang <73****@gmail.c om> 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(filena me)
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(filena me,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!!
Jul 18 '05 #2
Bryant Huang wrote:
Hello!

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.

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 usage is one of the reasons why the __import__ function exists (despite
what its docs say). It's right there at the top of the library reference's
'builtin functions' section:

http://www.python.org/dev/doc/devel/...-in-funcs.html

Instead of writing "import foo as mod" you can write "mod = __import__('foo ')".
The first is better when you do know the name of the module you want at coding
time, but the latter is handy when you want to be dynamic about it.

Cheers,
Nick.

--
Nick Coghlan | nc******@email. com | Brisbane, Australia
---------------------------------------------------------------
http://boredomandlaziness.skystorm.net
Jul 18 '05 #3
Ah, thanks a lot, Grant and Nick.

Let me try to clarify because I think I was unclear in specifying what
I want to do:

1. Read in a file containing a bunch of function definitions:

def f1(x):
...

def f2(x):
...

def f3(x):
...

def f4(x):
...

2. In wxPython, populate a CheckListBox with all the functions defined
in that file.

3. Allow the user to check some of the functions, say for example, f1()
and f3().

4. The program then executes f1() and f3() on some specified data.
The reason I asked these questions is because I don't know what
functions are contained in the function file ahead of time, but I still
want to be able to read those in, then based on which functions the
user selects, to run those accordingly, even though I still don't know,
at design-time, what functions are contained in the function file.

Does that make sense?

Thanks a lot!
Bryant

Jul 18 '05 #4
if the file you want to include is not txt, but instead py, it should
be easy.
for example you have fs.py

you just
-------------------------------------
fs=__import__(" fs")
f=[a for a in dir(fs) if a[0:2]!='__']
#no you have f1(),f2(),f3() as f[0],f[1],f[2]
then excute desired function, for example f2():
exec("fs."+f[1]+"()")
if you have top level variable in that file, just modify this to test
typs.FunctionTy pe(import types first)

Jul 18 '05 #5
Answer below...

"Bryant Huang" <73****@gmail.c om> wrote in message news:<11******* **************@ g14g2000cwa.goo glegroups.com>. ..
Hello!

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.

<snip>

===== [bar.txt] =====

def negate(x):
return -x

def square(x):
return x*x
===== [foo.py] =====

# open functions file
foo_file = open("bar.txt")
foo_lines = foo_file.readli nes()
foo_file.close( )
foo_str = "".join(foo_lin es)

# compile code
foo_code = compile(foo_str , "<string>", "exec")
foo_ns = {}
exec(foo_code) in foo_ns

# use functions
k = 5
print foo_ns["negate"](k) // outputs -5
print foo_ns["square"](k) // outputs 25
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()'.

Any pointers would be very welcome.

Thanks!
Bryant


You're actually very close here. The problem you are having is that
you are creating a local namespace (foo_ns) and executing that code
within that namespace. To "import" the functions into the global
namespace, exec them as:

exec foo_code in globals()
You will then be able to call the methods as if they had been declared
locally, ie. 'negate(5)' rather than 'foo_ns["negate"](5)'.

<plug type="shameless ">

I've written a simple line editor intended to be used within the
Python interactive interpreter, based on the old DOS 'edlin' command.
This is how I enable the user to "import" the entered functions into
their local namespace. The actual "execution" of the code is actually
pretty simple, and not much more involved than what you see here. You
may be able to get some more ideas, however.

For more info (or comments, suggestions, or pointers), check out
http://pyedlin.sourceforge.net).

</plug>
Here's a simple example that shows a "good" input loop:

====== Start exec example ======
if __name__ == '__main__':
funcdata = ['def func():\n', "\tprint 'Hello, world!'\n", '\n']

codeline = ''
for line in funcdata:
codeline += line
execline = codeline
if execline.endswi th('\n'):
execline = execline[:-1]

try:
obj = compile(execlin e, '<string>', 'exec')
except SyntaxError:
pass
else:
exec obj in globals()
codeline = ''

func()

====== End exec sample ======
Executing this code will print 'Hello, world!' to the console.
Hope this helps!

T.J.
Jul 18 '05 #6
I have to say, I was skeptical about your execution method at first --
simply joining all of the lines and then compiling them. My
understanding of the compile method from the documentation led me to
believe that you needed to process a line at a time. ''.join ing them
all seems to work very well, however, and it's a lot easier!

My comments about 'exec obj in globals()' still stand, however. Give
it a try and let me know if it works the way you expect.
T.J.

Jul 18 '05 #7
#--- file bar.py
def negate(n):
return -n

def square(n):
return n*n
#--- end bar.py
foo="bar"
fs=__import__(f oo)
import types
f=[a for a in dir(fs) if a[0:2]!='__' and type(getattr(fs ,a))==types.Fun ctionType] f ['negate', 'square'] n=5
exec("print fs."+f[0]+"(n)") -5 exec("print fs."+f[1]+"(n)")

25
Isn't the problem solved?

Jul 18 '05 #8
or don't use exec():
f=[getattr(fs,a) for a in dir(fs) if a[0:2]!='__' and
type(getattr(fs ,a))==types.Fun ctionType]
f [<function negate at 0x100a00>, <function square at 0x144038>] f[0](n) -5 f[1](n)

25

Jul 18 '05 #9
Wensheng wrote:
#--- file bar.py


<snip>
foo="bar"
fs=__import__(f oo)


<snip>

Wensheng:

The problem with this is that it assumes the text file is a valid
python file, and that the extension is ".py". This may work for the
OP's situation; he would need to weigh in. 'exec'ing the functions
into the global namespace allows you to create functions from any
text-based source -- registry keys, ini files, user input, etc.
T.J.

Jul 18 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
2719
by: OneSolution | last post by:
Hi All, Here's what I'm trying to do. I have a diverse customer base, and as it grows, it's increasingly harder to figure out what aspect of our web site is selling and what is not. So I've been trying to use PHP (and/or ASP) to do some research on my customers. So I nosed around some web sites and found the following piece of code. <IMG
1
11477
by: Cindy Lee | last post by:
I need to insert rows into MySql database from oracle, which I imagine is a rather common task. The path I decided to take is write a java procedure, as recommended in the manual. However, java expects a driver to connect to mysql, so I use the driver that everyone is using, mysql-connector-java-3.0.11-stable-bin.jar that can be downloaded from www.mysql.com. There are sources that come with it, but they are rather complex to build and...
10
4883
by: sneill | last post by:
Using XMLHTTP and DOM I'm able to load new HTML page content. I'd now like to load small snippets of javascript with the HTML markup and have that <script> incorporated into the page. If any of the loaded script exists outside a function definition (eg: a call to a function), I'd like that code to be executed as soon as its added to the DOM. Can anyone suggest the best way to do this? I've Googled but not found anything comprehensive....
1
8062
by: Torrent | last post by:
The Following is an Error I am getting using VS.NET 2003. When I bind the XML and XSLT Document together in Internet Explorer it works fine. However when I attempt to Load the File with the XSLTTransform.Load it raises this error. I have attempted to use a DNS Resolver hoping that I could get it to request a URI or URN that i could return a Custom XSLT Context to (or something - grasping at straws since nobody else seems to have documented the...
2
2143
by: NGM | last post by:
Hello All I have a unmanaged C++ DLL, which has been wrapped up with a manged C++ DLL. When i refer to this managed DLL in Windows form based applications it works out fine. But when i refer to the the same managed C++ DLL in ASP.Net application. ngmujumdar@hotmail.com/ amar_a_k@yahhoo.co NG
76
4088
by: kwilder | last post by:
This works, but it doesn't load the latest version of the xml if it was just modified without closing and reopening the browser. Here's the scenario: I have an xml doc called results.xml. It can contain lots of data. <Results> <Data>Stuff</Data> <Data>More stuff</Data>
7
10962
by: R Reyes | last post by:
Can someone please explain to me why I can't get the MS Word Interop assembly to work in my VS2005 project? I'm trying to manipulate MS Word from my Web Form application and I can't get passed this screen below. Please help, thanks in advance... Configuration Error Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify...
4
1406
by: WT | last post by:
Hello, I have copied my web site to a test server(W2K3), this web site is using a reference to an assembly that wraps all the calls to 2 web services (MS CRM 3.0). This runs perfectly on my dev environement, but when I copy the web site using VS2005, I get the following error when trying to run the application: Could not load file or assembly 'Microsoft.Crm.MetadataService, Version=3.0.5300.0, Culture=neutral,...
5
1537
by: Cenk Genisol | last post by:
Hi NG, I am relatively new to Web developement and have some questions to you. I've got a Masterpage where some graphics are embedded by CSS. They format the borders of tables, which store page content so it's just an optical background. During the process of loading the page on the client, pages which implement the above mentioned masterpage are build very excursive. That looks
20
4302
by: Nickolai Leschov | last post by:
Hello all, I am programming an embedded controller that has a 'C' library for using its system functions (I/O, timers, all the specific devices). The supplied library has .LIB and .H files. How can I dynamically load a LIB file and access all its functions? Surely someone has solved similar task? My intention is to use a Forth system for programming the controller,
0
9456
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9275
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10034
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9872
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9713
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7248
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5142
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5304
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2666
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.