473,804 Members | 1,971 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

ConfigParser: Can I read(ConfigPars er.get()) a configuration file anduse it to call a funciton?

Hello. I am a novice programmer and have a question

I have a configuration file(configurat ion.cfg)
I read this from reading.py using ConfigParser
When I use ConfigParser.ge t() function, it returns a string.
I want to call a function that has the same name as the string from
the configuration file.
configuration.c fg
---------------------------------------
[1234]
title: abcd
function: efgh
---------------------------------------
reading.py
--------------------------------------------------------
import ConfigParser

def efgh():
print 'blah'

config = ConfigParser.Co nfigParser()
config.read('co nfiguration.cfg ')

fcn = config.get('123 4','function')
type(fcn)
print fcn
--------------------------------------------------------

<type 'str'>
efgh
Is there any way to call efgh() ?
One way I know is using if statement
if fcn == 'efgh':
efgh()

But I am going to have many functions to call, so I want to avoid
this.
Thank you for your help
Jun 27 '08 #1
3 1547
Le Thursday 26 June 2008 16:41:27 ja********@gmai l.com, vous avez écrit*:
Hello. I am a novice programmer and have a question

I have a configuration file(configurat ion.cfg)
I read this from reading.py using ConfigParser
When I use ConfigParser.ge t() function, it returns a string.
I want to call a function that has the same name as the string from
the configuration file.

You can find the function in the global dictionary (returned by globals()):

globs = globals()
func_name = config.read('12 34', 'function')
func = globs[func_name]

# and then call it
func()

But a safer way would be to use a class with some static methods:

class Functions (object) :

@staticmethod
def efgh () :
blah blah...

and then find the function in the class dict:

func = getattr(Functio ns, func_name)
func()

this way you can restrict the set of functions the user can give, excluding
those which are not supposed to be called this way.

--
Cédric Lucantis
Jun 27 '08 #2
On Jun 26, 7:41*am, jamitwi...@gmai l.com wrote:
Hello. I am a novice programmer and have a question

I have a configuration file(configurat ion.cfg)
I read this from reading.py using ConfigParser
When I use ConfigParser.ge t() function, it returns a string.
I want to call a function that has the same name as the string from
the configuration file.

configuration.c fg
---------------------------------------
[1234]
title: abcd
function: efgh
---------------------------------------

reading.py
--------------------------------------------------------
import ConfigParser

def efgh():
* *print 'blah'

config = ConfigParser.Co nfigParser()
config.read('co nfiguration.cfg ')

fcn = config.get('123 4','function')
type(fcn)
print fcn
--------------------------------------------------------

<type 'str'>
efgh

Is there any way to call efgh() ?
One way I know is using if statement
if fcn == 'efgh':
* *efgh()

But I am going to have many functions to call, so I want to avoid
this.

Thank you for your help
Something like this:
globals()[fcn]()
Jun 27 '08 #3
Thank you for the answers.
Now I understood how to call a function, let me ask you another
question.

configuration.c fg
---------------------------------------
[1234]
title: abcd
function: efgh
---------------------------------------

reading.py
--------------------------------------------------------
import ConfigParser

class Functions:
def efgh(self):
print 'blah'

fcn = Functions()

config = ConfigParser.Co nfigParser()
config.read('co nfiguration.cfg ')
title = config.get('123 4','title') # number 1
function_name = config.get('123 4','function')

title = getattr(fcn, function_name)
title()
--------------------------------------------------------

instead of assigning string value('abcd') to title at number 1

I want to assign this function(fcn.ef gh()) to abcd and make abcd a
FunctionType.
so later on, I want to call it by abcd(), not title().
The reason is I will have a loop reading from configuration file, so I
need to have different names for each function.
abcd is a string I read got it from config.get('123 4','title')

Thanks again.
Jun 27 '08 #4

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

Similar topics

2
8685
by: Alexander Kienzle | last post by:
I'm new to Java programming. I'm developing a Servlet for tomcat which needs an external configuration file. With external I mean a file (in XML format) which is customizable and not contained in my package. I don't want to hardcode any path and I would like to be independent of the application server (tomcat, websphere,...). Until now, I put the file in my package and open it using obj.getClass.getResourceAsStream but when I put my...
2
2024
by: Al Repasky | last post by:
The program I have written with VB/NET 2003 has a Myapp.exe.config file that I did not know I would be creating. My program using an Access db and can not find the DB file after building the executable. When this config file is there it runs ok and when it is not there it can not find the DB file. When I put the program on another computer it can not find the DB file either way. Does anyone have an idea what is happening? Thanks, Al
1
2860
by: Paul Fi | last post by:
I have this problem with .NET remoting: my remote class is called RemoteHandler which implements an interface called IEazyRemoting which has only one method to be implemented which is my server configuration file looks like this: <configuration> <system.runtime.remoting> <application> <service>
2
1830
by: Peter | last post by:
Hello, Thanks for reviewing my question. I am trying to understand how to use a configuration file for my application, so I can turn debug or trace with a switch. The following is what I put together from my understanding but doesn't work. AssemblyInfo.cs ------------------
7
1529
by: serge calderara | last post by:
Dear all, I am building an ASP 1.1 application based on a n-Tier architecture. I have my datalayer class that need to read the connection string of my sql server database from a configuration file as it can be located anywhere. Do I have to add a web.config file within my class library project and call my AppSetting section with standard .Net function or do I have to do it in an other way around ?
2
1208
by: genojoe | last post by:
http://msdn2.microsoft.com/en-us/library/system.configuration.configuration This site contains sample code that does not compile for me. The line of code is: ' Get the current configuration file. Dim config As _ System.Configuration.Configuration = _ ConfigurationManager.OpenExeConfiguration( _ ConfigurationUserLevel.None)
5
4604
by: Water Cooler v2 | last post by:
I know that we can add a single name value entry in app.config or web.config in the configuration/configSettings/appSettings section like so: <add key="key" value="value" /> Question: I want to add a dictionary of name-value pairs. In other words, instead of a single name-value, I want to add a name-value collection in there. I could do this:
3
2228
by: guybenron | last post by:
Hey, I have a sort of petty-neurotic question, I'm kinda pedantic and like to keep my log directories clean, and this thing is bothering me to the point of actually posting a question (couldn't find any post about this..). My application has two types of components: daemons and regular ones that are run every on crontab. Because the log structure is very similar, I want both to use the same logging configuration file.
5
2085
by: Author | last post by:
This may sound like a silly question. I rarely do console or windows form applications. In a console application, I have an XML configuration file. I place it under my application root. In my code, I also say string configFilePath = "./configuration.xml"; When I debug the application with VS 2005, I get an error which says
0
9711
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
9593
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
10595
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...
1
10335
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10088
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...
0
9169
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 launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6862
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 into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5668
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3001
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.