473,480 Members | 1,980 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Cannot import a module from a variable

Hi all:

I try to do things below:
>>>import sys
for i in sys.modules.keys():
import i
Traceback (most recent call last):
File "<pyshell#67>", line 2, in <module>
import i
ImportError: No module named i

But it seems that import donot know what is i ? why?

Thanks/

Oct 15 '06 #1
10 2093
"Jia Lu" <Ro*****@gmail.comwrites:
Hi all:

I try to do things below:
>>>>import sys
for i in sys.modules.keys():
import i
Traceback (most recent call last):
File "<pyshell#67>", line 2, in <module>
import i
ImportError: No module named i

But it seems that import donot know what is i ? why?
Try using __import__(i) instead.

--
Christian Joergensen | Linux, programming or web consultancy
http://www.razor.dk | Visit us at: http://www.gmta.info
Oct 15 '06 #2
Christian Joergensen wrote:
"Jia Lu" <Ro*****@gmail.comwrites:
>Hi all:

I try to do things below:
>>>>import sys
for i in sys.modules.keys():
import i
Traceback (most recent call last):
File "<pyshell#67>", line 2, in <module>
import i
ImportError: No module named i

But it seems that import donot know what is i ? why?

Try using __import__(i) instead.
(a) you need something like exec('import ' + i) for most cases
but (b) "encodings" is a package i.e. it points to a directory which has
an __init__.py file.

Colin W.

Oct 15 '06 #3
Jia Lu wrote:
Hi all:

I try to do things below:
>>>import sys
for i in sys.modules.keys():
import i
Traceback (most recent call last):
File "<pyshell#67>", line 2, in <module>
import i
ImportError: No module named i

But it seems that import donot know what is i ?
The import statement expects a name (a symbol), not a string.

--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Oct 16 '06 #4
On 16/10/06, Bruno Desthuilliers <on***@xiludom.growrote:
Jia Lu wrote:
Hi all:

I try to do things below:
>>import sys
for i in sys.modules.keys():
import i
Traceback (most recent call last):
File "<pyshell#67>", line 2, in <module>
import i
ImportError: No module named i

But it seems that import donot know what is i ?

The import statement expects a name (a symbol), not a string.
eval( 'import %s' % modname)

and

eval( 'reload(%s)' % modname)

Usual warnings about eval apply, but in this case it is usable.

HTH :)
Oct 17 '06 #5
Tim Williams wrote:
eval( 'reload(%s)' % modname)
reload takes a module object, not a module name. since you need to have the
object, you might as well pass it to the reload() function.

</F>

Oct 17 '06 #6
"Tim Williams" <ti*@tdw.netwrote:
>The import statement expects a name (a symbol), not a string.

eval( 'import %s' % modname)

and

eval( 'reload(%s)' % modname)

Usual warnings about eval apply, but in this case it is usable.
Did you actually try your suggestion before posting?
>>modname = 'os'
eval( 'import %s' % modname)
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
eval( 'import %s' % modname)
File "<string>", line 1
import os
^
SyntaxError: invalid syntax
>>>
Also, it is pretty pointless to import the module and not know which
arbitrary variable name it will have created. It is much simpler just to
use the __import__ builtin:
>>module = __import__(modname)
module
<module 'os' from 'C:\Python25\lib\os.pyc'>

Oct 17 '06 #7
Hi,

This has actually been answered in a previous post ("user modules"
started by myself), for which I was very grateful. I have since
expanded on their solutions to create the following code, of which parts
or all may be useful. You'll probably be most interested in the last
part of the code, from "# Now we actually import the modules" onwards.
>>import os
import glob
# import_extension_modules(directory)
# Imports all the modules in the sub-directory "directory"
# "directory" MUST be a single word and a sub-directory of that
# name MUST exist.
# Returns then as a dictionary of {"module_name":module}
# This works for both .py (uncompiled modules)
# and .pyc (compiled modules where the source code is not given)
# TODO: Fix limitations above, clean up code.
#
def import_extension_modules(directory):
previous_directory = os.getcwd()
try:
os.chdir(directory)
uncompiled_files = glob.glob("*.py")
compiled_files = glob.glob("*.pyc")
all_files = []
modules = {}
for filename in uncompiled_files:
all_files.append(filename[0:-3]) # Strip off the ".py"
for filename in compiled_files:
# Add any pre-compiled modules without source code.
filename = filename[0:-4] # Strip off the ".pyc"
if filename not in all_files:
all_files.append(filename)
if "__init__" in all_files:
# Remove any occurrences of __init__ since it does
# not make sense to import it.
all_files.remove("__init__")
# Now we actually import the modules
for module_name in all_files:
# The last parameter must not be empty since we are using
# import blah.blah
# format because we want modules not packages.
# see 'help(__import__)' for details.
module = __import__("%s.%s" %(directory,module_name), None,
None,["some string to make this a non-empty list"])
modules[module.__name__] = module
return modules
finally:
os.chdir(previous_directory)
>>user_modules = import_extension_modules("user_modules")
user_modules
{'user_modules.funky_module': <module 'user_modules.funky_module' from
'C:\Projects\module_import_tester\src\user_modules \funky_module.pyc'>}

Woah, that actually works? Having the "finally" after the "return"?
That could make some things easier, and some things harder...

Hope that helps,

Cameron.
Oct 19 '06 #8
At Wednesday 18/10/2006 22:51, Cameron Walsh wrote:
previous_directory = os.getcwd()
try:
os.chdir(directory)
[ ... ]
return modules
finally:
os.chdir(previous_directory)

Woah, that actually works? Having the "finally" after the "return"?
That could make some things easier, and some things harder...
Note that moving the return statement after the finally does
*exactly* the same thing, generates shorter code, and is a lot more
readable (IMHO).
--
Gabriel Genellina
Softlab SRL

__________________________________________________
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya!
http://www.yahoo.com.ar/respuestas

Oct 19 '06 #9
Gabriel Genellina wrote:
At Wednesday 18/10/2006 22:51, Cameron Walsh wrote:
> previous_directory = os.getcwd()
try:
os.chdir(directory)
[ ... ]
return modules
finally:
os.chdir(previous_directory)

Woah, that actually works? Having the "finally" after the "return"?
That could make some things easier, and some things harder...

Note that moving the return statement after the finally does *exactly*
the same thing, generates shorter code, and is a lot more readable (IMHO).

I wholeheartedly agree, the above version is hideous. It was a
copy-paste error that got it after the return statement and I was
surprised to see it actually worked.
Oct 19 '06 #10
Cameron Walsh wrote:
Woah, that actually works? Having the "finally" after the "return"?
That could make some things easier, and some things harder...
The whole point of having a clean-up handler is to make sure it runs no
matter what:

When a return, break or continue statement is executed in the
try suite of a try-finally statement, the finally clause is also
executed "on the way out".

http://pyref.infogami.com/try

</F>

Oct 19 '06 #11

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

Similar topics

1
2044
by: Dan Williams | last post by:
Hi people I've just joined the Python list and although I'm sure my question must be asked fairly frequently, I have been unable to find an answer after two days of searching. For the record, my...
16
2724
by: Manlio Perillo | last post by:
Hi. I'm a new user of Python but I have noted a little problem. Python is a very good language but it is evolving, in particular its library is evolving. This can be a problem when, ad example,...
2
1642
by: David MacQuigg | last post by:
I'm setting up a large hierarchy of module packages and using a variable to select which of many alternative packages to import. For example, the variable 'config.modsel' points to a particular...
4
2176
by: MackS | last post by:
Hi I'm new to Python, I've read the FAQ but still can't get the following simple example working: # file main_mod.py: global_string = 'abc' def main():
8
5443
by: baustin75 | last post by:
Posted: Mon Oct 03, 2005 1:41 pm Post subject: cannot mail() in ie only when debugging in php designer 2005 -------------------------------------------------------------------------------- ...
1
4605
by: vsp15584 | last post by:
Hii..i use the coding as below :- import java.applet.applet; import java.awt.*; import com.sun.j3d.utils.applet.mainframe; import com.sun.j3d.utils.universe.*; import...
4
2810
by: Chris8Boyd | last post by:
I am embedding Python in a MSVC++ (2005) application. The application creates some environment and then launches a Python script that will call some functions exported from the MSVC++ application....
0
946
by: Gary Herron | last post by:
Dan Yamins wrote: Because loading (and reloading) assigns values to variables (called binding a value in Python), but does not go on a hunt to find variables to *unbind*. Once a variable is...
4
1233
by: bvdp | last post by:
Terry Reedy wrote: <snip> <snip> <snip>
0
7054
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
7102
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...
1
6756
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...
0
7003
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...
1
4798
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...
0
4495
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...
0
3008
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...
1
570
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
199
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...

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.