473,387 Members | 1,687 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

dynamically importing a module and function

Hi
I have a function data['function'], that I need to import from a file
data['module'], in the directory data['cwd']

If I do this from python interactive shell (linux fedora core 8) from
dir /home/mark it works fine:

cwd = data['cwd']
os.chdir(cwd)
print os.getcwd()
module = __import__(data['module'])
function = getattr(module, data['function'])

But if I put this in a file /home/mark/work/common/funcq.py and run it
from /home/mark, it throws me error like this.. how to fix this? it
imports the module successfully, but it is not looking for subsequent
modules in the os.getcwd()..

/home/mark/work/proj1
Traceback (most recent call last):
File "/home/mark/work/common/funcq.py", line 60, in <module>
if __name__ == '__main__':do()
File "/home/mark/work/common/funcq.py", line 33, in do
module = __import__(data['module'])
File "/home/mark/app.py", line 5, in <module>
import abcde
ImportError: No module named abcde
Jun 27 '08 #1
4 2139
rk*****@gmail.com wrote:
Hi
I have a function data['function'], that I need to import from a file
data['module'], in the directory data['cwd']
OT: Any good reason for using a dictionary instead of a class instance
(data.functiom, data.module, etc)?
>
If I do this from python interactive shell (linux fedora core 8) from
dir /home/mark it works fine:

cwd = data['cwd']
os.chdir(cwd)
print os.getcwd()
module = __import__(data['module'])
function = getattr(module, data['function'])
This is possibly due to python using what was the current working
directory when it started up.

An alternative (untested):

saved = sys.path
sys.path = data['cwd']
module = __import__(data['module'])
sys.path = saved

Exception handling is left as an exercise for the reader.

HTH,
John
Jun 27 '08 #2
On Mon, Apr 21, 2008 at 3:39 PM, John Machin <sj******@lexicon.netwrote:
rk*****@gmail.com wrote:
data['module'], in the directory data['cwd']
OT: Any good reason for using a dictionary instead of a class instance
(data.functiom, data.module, etc)?
not really, i just wanted to stick to primitive python data types.

If I do this from python interactive shell (linux fedora core 8) from
dir /home/mark it works fine:

cwd = data['cwd']
os.chdir(cwd)
print os.getcwd()
module = __import__(data['module'])
function = getattr(module, data['function'])
saved = sys.path
sys.path = data['cwd']
module = __import__(data['module'])
sys.path = saved
now the module gets loaded, but i am not able to get the function from
the module, though it works fine in the interactive-shell

Traceback (most recent call last):
File "/home/mark/work/common/funcq.py", line 62, in <module>
if __name__ == '__main__':do()
File "/home/mark/work/common/funcq.py", line 35, in do
function = getattr(module, data['function'])
AttributeError: 'module' object has no attribute 'new'
this works in shell though..
>>import os
os.chdir('/home/mark/work/proj1')
import sys
sys.path.append('/home/mark/work/proj1')
module = __import__('app')
function = getattr(module, 'new')
function(1)
1
Jun 27 '08 #3
rk*****@gmail.com wrote:
On Mon, Apr 21, 2008 at 3:39 PM, John Machin <sj******@lexicon.netwrote:
>rk*****@gmail.com wrote:
>>data['module'], in the directory data['cwd']
OT: Any good reason for using a dictionary instead of a class instance
(data.functiom, data.module, etc)?
not really, i just wanted to stick to primitive python data types.

>>If I do this from python interactive shell (linux fedora core 8) from
dir /home/mark it works fine:

cwd = data['cwd']
os.chdir(cwd)
print os.getcwd()
module = __import__(data['module'])
function = getattr(module, data['function'])

> saved = sys.path
sys.path = data['cwd']
module = __import__(data['module'])
sys.path = saved

now the module gets loaded, but i am not able to get the function from
the module, though it works fine in the interactive-shell

Traceback (most recent call last):
File "/home/mark/work/common/funcq.py", line 62, in <module>
if __name__ == '__main__':do()
File "/home/mark/work/common/funcq.py", line 35, in do
function = getattr(module, data['function'])
AttributeError: 'module' object has no attribute 'new'
this works in shell though..
>>>import os
os.chdir('/home/mark/work/proj1')
import sys
sys.path.append('/home/mark/work/proj1')
module = __import__('app')
function = getattr(module, 'new')
function(1)
1
It's not at all obvious that the "works in shell" code is the same as
the code in your script.

Consider the possibility that as a result of frantic experimentation you
have multiple copies of app.* with varying contents lying around.

Try this in your script so that you can see exactly what it is doing,
instead of comparing it to a strawman:
print "attempting to import", whatever
module = __import__(whatever)
print "got", module.__name__, "from", os.path.abspath(module.__file__)
print "module contents":, dir(module)
Jun 27 '08 #4
On Mon, Apr 21, 2008 at 4:47 PM, John Machin <sj******@lexicon.netwrote:
saved = sys.path
sys.path = data['cwd']
module = __import__(data['module'])
sys.path = saved
>
import os
os.chdir('/home/mark/work/proj1')
import sys
sys.path.append('/home/mark/work/proj1')
module = __import__('app')
function = getattr(module, 'new')
function(1)
>

>
1

It's not at all obvious that the "works in shell" code is the same as the
code in your script.

Consider the possibility that as a result of frantic experimentation you
have multiple copies of app.* with varying contents lying around.
thanks a lot!
there was a file app.pyc lying around in the dir from which i was
running the script...
Jun 27 '08 #5

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

Similar topics

1
by: J. Kenney | last post by:
Good Morning, Is there a way for a function called within an _imported_ library to call back to _calling_ python program to run a function? (Shown below) Also can you overload the print...
0
by: Mark English | last post by:
Basic problem: If there is a C-extension module in a package and it tries to import another python module in the same package without using the fully qualified path, the import fails. Config:...
12
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...
4
by: jean-marc | last post by:
As an application programmer, I'm not well versed in the material aspects of computing (memory, cpu, bus and all). My understanding of imports in Python is such: the __main__ program is the center...
7
by: hg | last post by:
Hi, I have the following problem. I find in a directory hierarchy some files following a certain sets of rules: ..../.../../plugin/name1/name1.py ..... ..../.../../plugin/namen/namen.py
4
by: rshepard | last post by:
I'm stymied by what should be a simple Python task: accessing the value of a variable assigned in one module from within a second module. I wonder if someone here can help clarify my thinking. I've...
5
by: Matt_D | last post by:
Good afternoon. As a self-tutoring project I am writing a one-time-pad encrypt/decrypt script. I have completed the encryption portion and am working currently on the decryption algorithm. My...
0
by: rkmr.em | last post by:
there was a mistake in my prev mail.. it is not able to successfully import the module. abcde is in directory /home/mark/work/proj1, but it is looking for it in /home/mark from where i am...
11
by: Nadeem | last post by:
Hello all, I'm trying to write a function that will dynamically generate other functions via exec. I then want to be able to import the file (module) containing this function and use it in other...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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,...
0
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...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

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.