Reputation: 33
I'm currently working on a Django-Project that amongst others has to read different file-formats. Each format got its own reading-script. The formats to be used depend on a choice, that is why the corresponding scripts are imported at run-time by my admin_view.py. That's done via imp:
module = imp.load_source('lidardaten.datatypes.' + datatype, PATH + datatype + '.py')
Now, my problem is, that i get an ImportError while trying to import the os-module within these scripts saying 'No module named path'.
Environment:
Request Method: POST
Request URL: http://lidardaten/django/lidardata/admin/upload/measurement/add/
Django Version: 1.2.5
Python Version: 2.4.3
Installed Applications:
['django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.admin',
'lidardata.upload']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.middleware.csrf.CsrfResponseMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
Traceback:
File "/usr/lib/python2.4/site-packages/django/core/handlers/base.py" in get_response
100. response = callback(request, *callback_args, **callback_kwargs)
File "/s1lidar/u1/mathias/www/lidardata/upload/admin_views.py" in add_measurement
127. module = imp.load_source('lidardaten.datatypes.' + datatype, PATH + datatype + '.py')
File "/s1lidar/u1/mathias/www/lidardata/datatypes/polly.py" in ?
1. import os
File "/usr/lib64/python2.4/os.py" in ?
133. from os.path import (curdir, pardir, sep, pathsep, defpath, extsep, altsep,
Exception Type: ImportError at /admin/upload/measurement/add/
Exception Value: No module named path
I don't have a problem importing the os-module neither whitin the admin_view.py nor via interpreter. Also importing other modules within the reading-scripts works fine - as long as those modules don't try to import os.
Is it because of importing the scripts with imp.load_source
? Other possibilities? Any suggestion would be skyscraper-highly appreciated!
Upvotes: 3
Views: 1123
Reputation: 2652
Rather than using imp
, have a look at the magic method __import__
, which can import modules without using filenames. Your code will end up something like:
module_name = 'polly'
module = getattr(__import__('lidardaten.datatypes', globals(), locals(), [module_name]), module_name)
Upvotes: 1