468,285 Members | 1,540 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,285 developers. It's quick & easy.

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 1922
"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 discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

1 post views Thread by Dan Williams | last post: by
16 posts views Thread by Manlio Perillo | last post: by
2 posts views Thread by David MacQuigg | last post: by
1 post views Thread by vsp15584 | last post: by
reply views Thread by Gary Herron | last post: by
4 posts views Thread by bvdp | last post: by
reply views Thread by NPC403 | last post: by
2 posts views Thread by MrBee | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.