473,563 Members | 2,797 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

how to get function names from the file

I have got names of functions stored in the file. For the simplicity
expect one row only with two function names: printFoo, printFOO
In my code I would like to define functions and then to read function
names from the file, so the functions can be executed in the order the
function names are stored in a file.

While trying to read the names from the file I am getting always
"strings" and I am not able to execute them.

I would like to write my code so it will look something like:

def printFoo():
print "foo"

def printFOO():
print "FOO"

# here I would like to read the file with the function names sequences
# and to create tuple which will contain the function names.
# After that I would like to call functions from the tuple:

functions=(prin tFoo, printFOO)
for function in functions:
function()

Thanks for your postings
Petr Jakes

Feb 15 '06 #1
7 2114
Try the following:

def printFoo():
print "Foo"

def printFOO():
print "FOO"

functions = ("printFoo", "printFOO") # list or tuple of strings from
file, or wherever
for function in functions:
call = function + "()"
eval(call)

Feb 15 '06 #2
Petr Jakes wrote:
I have got names of functions stored in the file. For the simplicity
expect one row only with two function names: printFoo, printFOO
In my code I would like to define functions and then to read function
names from the file, so the functions can be executed in the order the
function names are stored in a file.

While trying to read the names from the file I am getting always
"strings" and I am not able to execute them.

I would like to write my code so it will look something like:

def printFoo():
print "foo"

def printFOO():
print "FOO"

# here I would like to read the file with the function names sequences
# and to create tuple which will contain the function names.


If the functions are in the same module as the calling code:
functions=('pri ntFoo', 'printFOO')
for function in functions:
globals()[function]()

If the functions are in a 'functions' module:
funcs=('printFo o', 'printFOO')
for function in funcs:
getattr(functio ns, function)()

Kent
Feb 15 '06 #3
The following will return a dictionary containing the names and
functions of all the public functions in the current module. If a
function starts with an underscore _, it is considered private and not
listed.

def _ListFunctions( ):
import sys
import types
d = {}
module = sys.modules[__name__]
for key, value in module.__dict__ .items():
if type(value) is types.FunctionT ype:
fnname = value.__name__
if fnname[0] != '_':
d[value.__name__] = value
return d

Feb 15 '06 #4

"Petr Jakes" <mc********@gma il.com> wrote in message
news:11******** **************@ g14g2000cwa.goo glegroups.com.. .
I have got names of functions stored in the file. For the simplicity
expect one row only with two function names: printFoo, printFOO
In my code I would like to define functions and then to read function
names from the file, so the functions can be executed in the order the
function names are stored in a file.

While trying to read the names from the file I am getting always
"strings" and I am not able to execute them.

I would like to write my code so it will look something like:

def printFoo():
print "foo"

def printFOO():
print "FOO"
Make a dict mapping names to functions:

funs = {'printFoo':pri ntFoo, 'printFOO':prin tFOO}
# here I would like to read the file with the function names sequences
# and to create tuple which will contain the function names.
# After that I would like to call functions from the tuple:


Actually, str.split, the easiest way to separate the multiple names on a
line, gives you a list. Same difference to 'for'.

funnames=('prin tFoo', 'printFOO')
for fname in funnames:
funs[fname]()

Terry Jan Reedy

Feb 15 '06 #5
Petr Jakes wrote:
I have got names of functions stored in the file. For the simplicity
expect one row only with two function names: printFoo, printFOO
In my code I would like to define functions and then to read function
names from the file, so the functions can be executed in the order the
function names are stored in a file.

While trying to read the names from the file I am getting always
"strings" and I am not able to execute them.

I would like to write my code so it will look something like:

def printFoo():
print "foo"

def printFOO():
print "FOO"

# here I would like to read the file with the function names sequences
# and to create tuple which will contain the function names.
# After that I would like to call functions from the tuple:

functions=(prin tFoo, printFOO)
for function in functions:
function()

Thanks for your postings
Petr Jakes

I would do this as follows:

Create dictionary with the function names as keys and the pointer to
function definition as value:

fdict={'printFo o': printFoo, 'printFOO': printFOO}
functions=('pri ntFoo', 'printFOO')
for function in function:
if fdict.has_key(f unction: fdict[function]()
else:
print "No function named=%s defined" % function

-Larry Bates

Feb 16 '06 #6
Petr Jakes wrote:
I have got names of functions stored in the file. For the simplicity
expect one row only with two function names: printFoo, printFOO
In my code I would like to define functions and then to read function
names from the file, so the functions can be executed in the order the
function names are stored in a file.
Somehow, when people invent little languages like you are doing now,
the languages tend to grow over time...until you realize that you
should have written the scripts in Python... It's all up to you of
course, but making your code contain proper Python code might be
something to consider. Little languages are sometimes useful.

lu************* @gmail.com wrote: functions = ("printFoo", "printFOO") # list or tuple of strings from
file, or wherever
for function in functions:
call = function + "()"
eval(call)
I wouldn't do this. eval has security issues, and it's
overkill for simply finding names in a namespace as you
saw in the other replies.

Kent Johnson wrote: If the functions are in the same module as the calling code:
functions=('pri ntFoo', 'printFOO')
for function in functions:
globals()[function]()
and Larry Bates wrote (slightly corrected): Create dictionary with the function names as keys and the pointer to
function definition as value:

fdict={'printFo o': printFoo, 'printFOO': printFOO}
functions=('pri ntFoo', 'printFOO')
for function in functions:
if fdict.has_key(f unction): fdict[function]()
else:
print "No function named=%s defined" % function


These two options are basically the same. The
difference is that Kent suggest that you use a
mapping of names to functions provided by Python,
while Larry suggests that you make one yourself.
(BTW, instead of globals() you might want locals()
depending on what scope your functions are defined
in.)

While Kent's suggestion is a little less work, Larry's
suggestion buys you some more benfits:

- You can use other names than the actual function names
as keys in the dict. This means that:
-You can use reserved words (in, while etc) in your little
script
-You can rename functions and reorganize your code without
breaking your scripts.
-You can have command names in your script that contain
national characters, spaces, punctuation, start with digits,
etc (won't, stop!, 1st time, 1.2.45.start etc).

- It's safer: You control exactly what functions the
script might call. Those who write code you run eval
on can basically get arbitrary code executed.

$ cat > evil.py
print "Gotcha"
$ python
[snip]
def x(): print 'Ok' .... eval('x'+'()') Ok eval('__import_ _("evil") and x'+'()')

Gotcha
Ok

If you want more than just function names in your minilanguage,
you might want to have a look at the shlex module.
Feb 17 '06 #7
"eval" is not necessary in this case.
If you have a tuple with function names such as this: x=(printFoo,
printFOO)

you can execute them this way:
for f in x:

f()

Feb 17 '06 #8

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

Similar topics

9
4940
by: Penn Markham | last post by:
Hello all, I am writing a script where I need to use the system() function to call htpasswd. I can do this just fine on the command line...works great (see attached file, test.php). When my webserver runs that part of the script (see attached file, snippet.php), though, it doesn't go through. I don't get an error message or...
9
2990
by: drhowarddrfinedrhoward | last post by:
I see a number of pages with functions like MM_somefunction(). Where does the MM_ come from? I don't see it in any books I'm studying.
21
3822
by: Rob Somers | last post by:
Hey people, I read a good thread on here regarding the reason why we use function prototypes, and it answered most of my questions, but I wanted to double check on a couple of things, as I am writing something up on functions, and I don't like writing about things I am not sure about. Ok, then, here we go: I initially thought that one...
12
404
by: Eric | last post by:
I've got a pretty large C program with global variables and function names strewn about (i.e. no "static" declarations in front of them). Now I want to expose the ability for user's to supply their own shared object / dll code which will link with my large ugly program. Problem: naming collisions. If my program has: void...
3
1824
by: Luke | last post by:
I'm pretty stuck at the moment and wondering if anyone can spot the problem. Trying to create a function that will read a text file into a list and return that list. I wrote the following function and saved it as 'fileloader.py' def fileload(fname): infile=open(fname) dates = times=
3
4514
by: cybernerdsx2 | last post by:
Hi, I notice a function prototype being declared as following: FileStream.h ========= extern void openFile(char *__ident, int __option); But, in the function declaration part shown as following: FileStream.c
3
12724
by: Rico | last post by:
Hello, I have a generic process that logs errors from different sources. When I call this code, I'd like to also submit the name of the function or sub that is raising the error without having to manually type this in for each instance. For instance, (air code to follow) Public Sub LogMyError( errNumber as int, errDescription as string,...
13
1818
by: Jim Mackellan | last post by:
In my opinion, C not mungling its function names imposes unnecessary complexity on C++, requiring extern 'C' { ... } everywhere in headers. I believe that in the next version of the ISO standard, C should move to mungling its function names consistently with C++ to improve interoperability. Acutally this should have happened long ago. ...
16
3259
by: Xiaoxiao | last post by:
Hi, I got a C library, is there a way to view the public function names in this library so that I can use in my C program? Thanks.
0
7888
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. ...
0
8106
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...
0
7950
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...
0
6255
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5484
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...
0
5213
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3643
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...
1
2082
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1200
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.