473,761 Members | 8,372 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Question about import and sys.path

Hi all

I am writing a business/accounting application. Once a user has logged
in they are presented with a menu. Each menu option has a description
and an associated file name and program name. The file name is the name
of a .py file (impName) and the program name is the name of a class in
that file which I instantiate to run the program (progName).

When a menu option is selected, I execute the program like this -
imp = __import__(impN ame)
app = getattr(imp,pro gName)()

All the .py files are stored in one directory, which I add to sys.path
at the beginning of the session. It all seems to work fine.

Now my program directory is getting cluttered, so I want to split it
into sub-directories, one per company (it is a multi-company system). I
can do that, and each of the subdirectories can be added to sys.path,
so it should work as at present.

However, I want the ability to have duplicate program names stored in
different subdirectories. At the time of selecting the menu option I
know which company is active, so I know which directory I want to run
the program from, but there does not seem to be a way to tell 'import'
to import from a particular directory. I could manipulate sys.path and
ensure that the correct company subdirectory is in the first position,
but that idea does not appeal to me. Maybe it is a good idea though - I
am open to suggestion.

Would 'execfile' be a good alternative? From what I can understand of
the docs it is almost equivalent, but I am not sure if there are any
implications. Here are some questions -

1. Does execfile create a .pyc file from a .py file, or does it compile
the contents of the file every time it is executed? If the latter, that
could create a performance problem.

2. The docs say 'it does not use the module administration -- it reads
the file unconditionally and does not create a new module'. What does
that mean? The main implication I can think of is that if the same
program is executed more than once in a given session, 'import' would
realise the second time that the module has already been imported, and
would not import it again, whereas 'execfile' would re-execute the file
every time. That could also create a performance hit, but I don't think
it would be too serious.

3. I assume that once a module has been imported, it stays in memory
for the life of the interpreter session. What happens with execfile?
Does it get garbage-collected after execution is complete?

4. Are there any other implications I should know about? I did read the
warning about modifying locals, but I don't do anything like that.

Thanks for any advice

Frank Millman

Nov 28 '06 #1
3 1630

Frank Millman wrote:
Hi all

I am writing a business/accounting application. Once a user has logged
in they are presented with a menu. Each menu option has a description
and an associated file name and program name. The file name is the name
of a .py file (impName) and the program name is the name of a class in
that file which I instantiate to run the program (progName).

When a menu option is selected, I execute the program like this -
imp = __import__(impN ame)
app = getattr(imp,pro gName)()

All the .py files are stored in one directory, which I add to sys.path
at the beginning of the session. It all seems to work fine.

Now my program directory is getting cluttered, so I want to split it
into sub-directories, one per company (it is a multi-company system). I
can do that, and each of the subdirectories can be added to sys.path,
so it should work as at present.

However, I want the ability to have duplicate program names stored in
different subdirectories. At the time of selecting the menu option I
know which company is active, so I know which directory I want to run
the program from, but there does not seem to be a way to tell 'import'
to import from a particular directory.
I suggest to use module `imp`.
For example:

I assume paths like this:

app/
importer.py
company1/
prog1.py
the module in the company1 subdirectory:

# prog1
class SomeClass(objec t):
def test(self):
return "%s: %s" % (__file__, self.__class__. __name__)

and the module with your menu could look like this:

# importer.py

def get_class(class name, impname, company):
fp, pathname, description = imp.find_module (impname, [company])
m = imp.load_module (impname, fp, pathname, description)
return getattr(m, classname)

obj = get_class("Some Class", "prog1", "company1") ()
print obj.test()

--
HTH,
Rob

Nov 28 '06 #2

Rob Wolfe wrote:
Frank Millman wrote:
Hi all

However, I want the ability to have duplicate program names stored in
different subdirectories. At the time of selecting the menu option I
know which company is active, so I know which directory I want to run
the program from, but there does not seem to be a way to tell 'import'
to import from a particular directory.

I suggest to use module `imp`.
For example:

I assume paths like this:

app/
importer.py
company1/
prog1.py
the module in the company1 subdirectory:

# prog1
class SomeClass(objec t):
def test(self):
return "%s: %s" % (__file__, self.__class__. __name__)

and the module with your menu could look like this:

# importer.py

def get_class(class name, impname, company):
fp, pathname, description = imp.find_module (impname, [company])
m = imp.load_module (impname, fp, pathname, description)
return getattr(m, classname)

obj = get_class("Some Class", "prog1", "company1") ()
print obj.test()
Perfect. Thanks very much, Rob.

One small point. The docs have the following warning -

"Important: the caller is responsible for closing the file argument, if
it was not None, even when an exception is raised. This is best done
using a try ... finally statement. "

I have added this to my code.

I wonder if you can avoid this in 2.5 by using the 'with' statement. I
am still using 2.4, so I cannot test. Anyway, your suggestion does
exactly what I want, and it works perfectly.

Thanks again.

Frank

Nov 29 '06 #3

Frank Millman wrote:
One small point. The docs have the following warning -

"Important: the caller is responsible for closing the file argument, if
it was not None, even when an exception is raised. This is best done
using a try ... finally statement. "

I have added this to my code.

I wonder if you can avoid this in 2.5 by using the 'with' statement. I
am still using 2.4, so I cannot test. Anyway, your suggestion does
exactly what I want, and it works perfectly.
Yes, of course. The `with` statement works exactly
as previously try...finally. I've tried it in 2.5 and it works
perfectly.
You have to use `from __future__ import with_statement` , though.
This statement will be always enabled in Python 2.6.

--
HTH,
Rob

Nov 29 '06 #4

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

Similar topics

11
23034
by: Jason Kratz | last post by:
OK. I've search on google groups and around the web for this and I haven't found an answer. I'm a Python newbie and have what I assume is a basic question. os.listdir takes a pathname as an arg but it doesn't actually list the contents of the dir I pass in. it always operates on the current dir (wherever the script is run) and I have to chdir beforehand. Is that how its supposed to work? If so what is the point in passing in a...
0
1906
by: Jason Kratz | last post by:
After figuring out the other day (thanks to everyone here who helped) how to get the dir lists I want on my unix machine I want to turn the same thing into an XML-RPC service. Using Simple XMLRPCServer.py I created my own version by adding my getdirs function and then I call the code to open the server: import os import os.path import SimpleXMLRPCServer import xmlrpclib
2
19018
by: kbass | last post by:
I would like to remove file that are older than 7 days old from a directory. I can do this in shell script rather easy but I would like to integrate this functionality into my Python program. How can this be achieved? Which module can be used to perform this tasks? Thanks! Shell Script example: find /path/to/dir -mtime +30 -exec rm '{}' \; Kevin
1
1658
by: Raaijmakers, Vincent \(GE Infrastructure\) | last post by:
Question: my src path looks like this: src\root\sub1 src\root\sub2 My main code is in root, lets say main.py and there is also a lib.py. In sub1 there if foo1.py and sub2 foo2.py Sorry for the long introduction...please don't stop reading... :-(
0
1994
by: John Roth | last post by:
I've found a case where it seems that Python is importing two copies of a module without any reason or indication. It took me a while to verify that this is what is occuring: I had to write a __import__ hook to trace the actual activity. The source code for the hook is below. There are several examples of the problem in the trace; this is one particularly juicy one. -----------Part 1 ---------------- '0059' Import 'TypeAdapter'...
5
2478
by: Steve Holden | last post by:
This is even stranger: it makes it if I import the module a second time: import dbimp as dbimp import sys if __name__ == "__main__": dbimp.install() #k = sys.modules.keys() #k.sort() #for kk in k:
5
2158
by: Pekka Niiranen | last post by:
Hi there, I have two scripts. The first "main.py" sets some variables and then imports another called "gen.py". The idea is to provide "main.py" that defines some paths, variables etc. without using Windows environment variables. Various other "hackers" will make additional Python scripts (subroutines) like "gen.py" that utilize variables set by the "main.py" and which "main.py" calls. I can do this with "subprocess" module by setting...
10
1440
by: erick_bodine | last post by:
I have a package directory structure as follows root- | Common (contains __init__.py file) WindowsComponents (contains __init__.py file) ... I would like modules in the WindowsComponents directory to be able to import some modules from the Common directory. In my first pass, I was
18
3390
by: bobueland | last post by:
IDLE doesn't seem to honor PYTHONSTARTUP environment variable nor sitecustomize.py How do you then customize in IDLE? (basically I want to execute the statement from btools import * each time I restart IDLEs Python Shell)
3
1094
by: Emin | last post by:
Dear Experts, I often find myself wanting to have a child module get some parameters defined in a parent module. For example, imagine I have the following directory structure and want something in baz.py to look at a value in config.py. I end up putting in things like import sys; sys.path.append('../..'). Is there a better way? foo/ __init__.py
0
9345
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
10115
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
9775
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
8780
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...
1
7332
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
6609
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
5229
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
5373
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3456
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.