You are not logged in.

#1 2005-10-17 12:10:37

Cam
Member
From: Brisbane, Aus
Registered: 2004-12-21
Posts: 658
Website

python, import and execfile

I'm working on a new adesklet, it's taking a bit of a modular approach, different modules are stored as files in the work directory and rather than import, I'm using execfile() to include them in the running code so I don't have to worry about scopes or anything. deskicon.py is the main script, and mount_icon.py is a module, if I import os.popen in mount_icon.py as it's required by that module but not others, it doesn't work. Imports only seem to take effect if they're in deskicon.py, I'm no expert at python so I don't know if this is the expected behaviour or not but if it is, is there a way I can import modules from mount_icon.py? I know I could do it if I imported mount_icon rather than execfile()'d it but this is working thus far and if I can get imports to work with minimal fuss that would be great lol

Any input would be greatly appreciated, thanks smile

Offline

#2 2005-10-17 14:07:43

cmp
Member
Registered: 2005-01-03
Posts: 350

Re: python, import and execfile

could you post a bit of code? a used exec or execfile a bit my self to trick python import mechanism.
btw.: you can also use exec file_object, as in
exec open('mount_icon.py')

Offline

#3 2005-10-17 14:23:36

Cam
Member
From: Brisbane, Aus
Registered: 2004-12-21
Posts: 658
Website

Re: python, import and execfile

execfile("%s.py" % self.config['engine'])
self.i = eval("%s(self.config)" % self.config['engine'])

That is the code that execfile()'s the file and then inits the class that was inside. It's probably a messy way to do it but Python doens't have variable variables like PHP and it's the best I could come up with on short notice. If I have an import statement inside the file that I pass to execfile(), it doesn't seem to take. It still errors out as if I'd never imported anything.

The whole code can be found here. It's been updated a bit since then but the deskicon.py file hasn't really changed, the out of date file in that archive is mount_icon.py smile

Offline

#4 2005-10-19 01:48:45

Cam
Member
From: Brisbane, Aus
Registered: 2004-12-21
Posts: 658
Website

Re: python, import and execfile

Okay, all sorted. Imports just chucked at the top of the file don't work, but if I place them inside a method that I know will get called (such as update() cause all the slogging gets done there) then it works fine big_smile

Offline

Board footer

Powered by FluxBB