473,625 Members | 3,134 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Mass importing of a template based system.. Trouble with name substitutions

Hi all,

Basically I have a bunch of pluggins in a directory (METDIR). For each
one of these templated pluggins I want to do a specific routine. Let's
start with a basic template

file example1.py
----------------
class example1:
def __init__(self):
print "Initialize "
def run(self):
print "Hi from example 1"
----------------

file example2.py
----------------
class example2:
def __init__(self):
print "Initalize"
def run(self):
print "example 2"
----------------

Now I want to go through each pluggin ( example1.py and example2.py )
and execute run. So here is my code but it doesn't work..
if os.path.isdir(M ETDIR):
modules = []

# Add the metrics dir toyour path..
sys.path.insert ( 0, os.getcwd() + "/" + METDIR )

for metric in glob.glob(METDI R+"/*.py"):
# Now lets start working on the individual metrics
module_name, ext = os.path.splitex t(os.path.basen ame(metric))
try:
module = __import__(modu le_name)
modules.append( module )
except ImportError , e:
print "Failed import of %s - %s" % ( module_name, e)
pass

for mod in modules:
a = mod.mod()
a.run()

But it doesn't work with the following..

Traceback (most recent call last):
File "./metriX.py", line 109, in main
a = mod.mod()
AttributeError: 'module' object has no attribute 'mod'

So it looks like it's not doing the substitution. Does anyone know how
I can do this?

Thanks much

Aug 4 '05 #1
6 1407
rh0dium wrote:
Hi all,

Basically I have a bunch of pluggins in a directory (METDIR). For each
one of these templated pluggins I want to do a specific routine. Let's
start with a basic template

file example1.py
----------------
class example1:
def __init__(self):
print "Initialize "
def run(self):
print "Hi from example 1"
----------------

file example2.py
----------------
class example2:
def __init__(self):
print "Initalize"
def run(self):
print "example 2"
----------------

Now I want to go through each pluggin ( example1.py and example2.py )
and execute run. So here is my code but it doesn't work..
if os.path.isdir(M ETDIR):
modules = []

# Add the metrics dir toyour path..
sys.path.insert ( 0, os.getcwd() + "/" + METDIR )

for metric in glob.glob(METDI R+"/*.py"):
# Now lets start working on the individual metrics
module_name, ext = os.path.splitex t(os.path.basen ame(metric))
try:
module = __import__(modu le_name)
modules.append( module )
except ImportError , e:
print "Failed import of %s - %s" % ( module_name, e)
pass

for mod in modules:
a = mod.mod()
a.run()

But it doesn't work with the following..

Traceback (most recent call last):
File "./metriX.py", line 109, in main
a = mod.mod()
AttributeError: 'module' object has no attribute 'mod'

So it looks like it's not doing the substitution.


Doing what substitution? Neither of the modules that you showed define a
mod() callable and nothing else seems to add one.

--
Robert Kern
rk***@ucsd.edu

"In the fields of hell where the grass grows high
Are the graves of dreams allowed to die."
-- Richard Harter

Aug 4 '05 #2
Hi again,

No you're right there isn't a mod.mod I want this to be evaluated from
this

for mod in modules:
a = mod.mod()
a.run()

to this.

for mod in modules:
a = example1.exampl e1()
a.run()

then

for mod in modules:
a = example2.exampl e2()
a.run()

etc.

So how is the substitution not working??
Robert Kern wrote:
rh0dium wrote:
Hi all,

Basically I have a bunch of pluggins in a directory (METDIR). For each
one of these templated pluggins I want to do a specific routine. Let's
start with a basic template

file example1.py
----------------
class example1:
def __init__(self):
print "Initialize "
def run(self):
print "Hi from example 1"
----------------

file example2.py
----------------
class example2:
def __init__(self):
print "Initalize"
def run(self):
print "example 2"
----------------

Now I want to go through each pluggin ( example1.py and example2.py )
and execute run. So here is my code but it doesn't work..
if os.path.isdir(M ETDIR):
modules = []

# Add the metrics dir toyour path..
sys.path.insert ( 0, os.getcwd() + "/" + METDIR )

for metric in glob.glob(METDI R+"/*.py"):
# Now lets start working on the individual metrics
module_name, ext = os.path.splitex t(os.path.basen ame(metric))
try:
module = __import__(modu le_name)
modules.append( module )
except ImportError , e:
print "Failed import of %s - %s" % ( module_name, e)
pass

for mod in modules:
a = mod.mod()
a.run()

But it doesn't work with the following..

Traceback (most recent call last):
File "./metriX.py", line 109, in main
a = mod.mod()
AttributeError: 'module' object has no attribute 'mod'

So it looks like it's not doing the substitution.


Doing what substitution? Neither of the modules that you showed define a
mod() callable and nothing else seems to add one.

--
Robert Kern
rk***@ucsd.edu

"In the fields of hell where the grass grows high
Are the graves of dreams allowed to die."
-- Richard Harter


Aug 4 '05 #3
rh0dium wrote:
for*mod*in*modu les:
a*=*mod.mod()
a.run()


Puzzle: If mod.mod did what you expect, what would a.run have to do to
maintain consistency?

There would be no way to determine the name of the module bound to the mod
variable, but fortunately the Python developers foresaw your problem and
stashed it (the name) in the __name__ attribute.
Use getattr(obj, attrname) to look up an attribute whose name is not known
at compile time:

for mod in modules:
a = getattr(mod, mod.__name__)()
a.run()

Peter

Aug 4 '05 #4

Peter Otten wrote:
rh0dium wrote:
for mod in modules:
a = mod.mod()
a.run()
Puzzle: If mod.mod did what you expect, what would a.run have to do to
maintain consistency?


I thought that once a = example.example the class is then loaded.
Since my framework defines a python file with a class named the same
within it. So

example1.py contains a class example1 and a module run
example2.py contains a class example2 and a module run
example3.py contains a class example3 and a module run

Additional methods that must be present within the class include a run
method. Since this was by definition I knew I needed to do a
substitution - namely mod.mod ( which was intended to be translated to
example1.exampl e1 ).

What you provided was very slick indeed. I no longer am dependant upon
the naming to get the job done.

Very nice - How does this work if some fool calls one class the same as
the other. I'm assuming the last class will be loaded - not the first.

There would be no way to determine the name of the module bound to the mod
variable, but fortunately the Python developers foresaw your problem and
stashed it (the name) in the __name__ attribute.
Use getattr(obj, attrname) to look up an attribute whose name is not known
at compile time:
OUTSTANDING!! Thanks so much!

for mod in modules:
a = getattr(mod, mod.__name__)()
a.run()

Peter


Aug 4 '05 #5
On 4 Aug 2005 07:25:51 -0700, "rh0dium" <sk****@pointci rcle.com>
declaimed the following in comp.lang.pytho n:

So how is the substitution not working??
What substitution?

"mod", as used in the loop, is just a name that is attached to a
module object... It is /not/ "example1", "example2", etc.

mod.mod()

The first mod is the name used inside the loop, and is associated with
the code of the current module. The .mod is an attribute that is
expected to be found inside the module object, and bears no relationship
to the mod used in the loop statement.

I'm having trouble coming up with a good simile... but...

Imagine your modules are envelopes in an inbox (on a desk).

for mod in modules: #modules is the inbox

is taking a post-it sticky note with "mod" written on it, and putting it
on the outside of an envelope.

a = mod.mod()

says, "take the envelope with 'mod' stuck to it, open it up, and look
for a sheet of paper with a SECOND sticky note 'mod' stuck to it, and
read the sheet of paper". When done, the "for" loop moves the outside
sticky note to the next envelope.

Your error message is telling you that none of the envelopes has
a sticky note "mod" INSIDE.

Try a dictionary instead of a list and see if the following
changes do anything for you.

modules = {}
for metric in glob.glob(METDI R+"/*.py"):
# Now lets start working on the individual metrics
module_name, ext = os.path.splitex t(os.path.basen ame(metric))
try:
module = __import__(modu le_name)
modules.append( module )
modules[module_name] = module
except ImportError , e:
print "Failed import of %s - %s" % ( module_name, e)
pass

for mod in modules:
for (name, mod) in modules.items() :
a = mod.mod()
a = getattr(mod, name)
a.run()


-- =============== =============== =============== =============== == <
wl*****@ix.netc om.com | Wulfraed Dennis Lee Bieber KD6MOG <
wu******@dm.net | Bestiaria Support Staff <
=============== =============== =============== =============== == <
Home Page: <http://www.dm.net/~wulfraed/> <
Overflow Page: <http://wlfraed.home.ne tcom.com/> <

Aug 4 '05 #6
On 4 Aug 2005 08:50:55 -0700, "rh0dium" <sk****@pointci rcle.com>
declaimed the following in comp.lang.pytho n:
Additional methods that must be present within the class include a run
method. Since this was by definition I knew I needed to do a
substitution - namely mod.mod ( which was intended to be translated to
example1.exampl e1 ).
But Python does NOT do "substitution". .. Variables (like "mod")
are just names attached to things, and have no bearing on any other
names that might be attached to the thing.
Very nice - How does this work if some fool calls one class the same as
the other. I'm assuming the last class will be loaded - not the first.

Uh... try it in the interactive prompt and see what happens?

-=-=-=- file x.py
def something():
print "I'm the something in X"

-=-=-=- file y.py
def something():
print "I'm the something in Y"

-=-=-=-= file main.py
import x
import y

y.something()
x.something()

z = y
z.something()

print id(x), id(y), id(z)

z.something = x.something
z.something()
y.something()

-=-=-=-=-=
I'm the something in Y
I'm the something in X
I'm the something in Y
16028080 16028528 16028528
I'm the something in X
I'm the something in X
-- =============== =============== =============== =============== == <
wl*****@ix.netc om.com | Wulfraed Dennis Lee Bieber KD6MOG <
wu******@dm.net | Bestiaria Support Staff <
=============== =============== =============== =============== == <
Home Page: <http://www.dm.net/~wulfraed/> <
Overflow Page: <http://wlfraed.home.ne tcom.com/> <

Aug 5 '05 #7

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

Similar topics

12
2380
by: qwweeeit | last post by:
The pythonic way of programming requires, as far as I know, to spread a big application in plenty of more manageable scripts, using import or from ... import to connect the various modules. In some cases there is a further complication: module importing through an indirect mechanism, like: exec "from " + xxx + " import *". A part the fact that I have not understood the "real" difference between import and from ... import (or also from......
0
1632
by: Chris F Clark | last post by:
In our C++ project we have some internal bug reporting macros that we use to get useful information when the program does something unexpected. Essentially at the point of the error, we invoke an internal interactive debugger that knows the classes within our system and allow us to walk around the objects that exist at the time of the fault. It mostly works fairly well. That catch being that we have to hand implement some of the code...
5
3171
by: dixie | last post by:
If I sent a user an empty database container - dB with no tables and I needed them to import their tables into it and one of their tables was a hidden table with the prefix Usys, is there any way in code I can get that table imported without them having to go to options and show hidden tables and then import it manually? dixie
6
2827
by: Stuart McGraw | last post by:
I am looking for a VBA "format" or "template" function, that is, a function that takes a format string and a varying number of arguments, and substitutes the argument values into the format string as specified in the format string. For example fmt("this is $1 format string. arg2 is $2", "short", 3) would return the string "this is short format string. arg2 is 3" Now, the above is easy to write and I have done so. What I want is...
29
4207
by: Natan | last post by:
When you create and aspx page, this is generated by default: using System; using System.Collections; using System.Collections.Specialized; using System.Configuration; using System.Text; using System.Text.RegularExpressions; using System.Web; using System.Web.Caching;
0
1484
by: I am Sam | last post by:
Ok I don't know what is the problem with my code But I am trying to build a newsletter that gathers parameters from 3 textbox controls and a Listbox control. The form then queries the event table based on 2 of the textboxes one for the start date of the events required and one for the last date of the events required. The 3rd textbox works fine. It passes the text from the textbox to the stringbuilder I built on the codebehind just fine....
5
2167
by: Mike Collins | last post by:
I am trying to export data from multiple tables in SQL Server to an XML file so I can then import it to another database. It seems to be working fine for exporting, but I am having trouble importing the file. I am getting the following error trying to import the same xml file I just exported. "System.Data.SqlClient.SqlException: Line 1: Incorrect syntax near 'GetTprsForExport'. Can someone show me where I am going wrong. Even though I say...
12
6207
by: JMO | last post by:
I can import a csv file with no problem. I can also add columns to the datagrid upon import. I want to be able to start importing at the 3rd row. This will pick up the headers necessary for the datagrid. Once I can get to that point I need some way to be able to add new data only to the new columns that were added. Here is some of my code: //Function For Importing Data From CSV File public DataSet ConnectCSV(string filetable)
0
8259
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
8696
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
8358
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
7188
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
5571
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
4195
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2621
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
1805
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1504
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.