473,395 Members | 1,701 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,395 software developers and data experts.

Generated code that is exec-ed (to simulate import) cannot importos.path??

Hello,
I don't understand why the following doesn't work.
What I want to do is dynamically import some generated
Python code and I'm doing this using compile and exec'ing
it in the dict of a new empty module object.
That works okay, but as soon as the generated code
tries do perform certain imports, it fails!
Certain other imports succeed. Consider this example code:
-----SNIP----
import imp

source="""
print 'importing random'
import random
print 'importing os'
import os
print 'bye!'

def getName():
return 'Hello there'
"""

newmod = imp.new_module('generated.testmodule')
code=compile(source,'<generated code>','exec')
print 'got code...'
exec code in newmod.__dict__
print 'done, newmod.getname(): ',newmod.getName()
-----/SNIP----
When run, it produces the following output:

[E:\test]python dynimport.py
got code...
importing random
importing os
Traceback (most recent call last):
File "dynimport.py", line 17, in ?
exec code in newmod.__dict__
File "<generated code>", line 5, in ?
File "C:\Python23\lib\os.py", line 131, in ?
from os.path import curdir, pardir, sep, pathsep, defpath, extsep, altsep
ImportError: No module named path
What's going on? Why can't it find os.path?

(Python 2.3.2, tested on linux and windows)

Confused,

Irmen.

Jul 18 '05 #1
4 2575
Irmen de Jong <irmen@-NOSPAM-REMOVETHIS-xs4all.nl> writes:
Hello,
I don't understand why the following doesn't work.
What I want to do is dynamically import some generated
Python code and I'm doing this using compile and exec'ing
it in the dict of a new empty module object.
That works okay, but as soon as the generated code
tries do perform certain imports, it fails!
Certain other imports succeed. Consider this example code: [snip] What's going on? Why can't it find os.path?


Dunno. Two things to try:

1) using new.module instead of the imp function
2) run python -v

Cheers,
mwh

--
CLiki pages can be edited by anybody at any time. Imagine the most
fearsomely comprehensive legal disclaimer you have ever seen, and
double it -- http://ww.telent.net/cliki/index
Jul 18 '05 #2
Irmen de Jong wrote:
Hello,
I don't understand why the following doesn't work.
What I want to do is dynamically import some generated
Python code and I'm doing this using compile and exec'ing
it in the dict of a new empty module object.
That works okay, but as soon as the generated code
tries do perform certain imports, it fails!
Certain other imports succeed. Consider this example code:
[...]
What's going on? Why can't it find os.path?


My trial and error findings (Python 2.3.2 on Linux):

Python gets confused by the module name "generated.testmodule", when
a "generated" package does not exist; it seems to look for
"generated.posixpath" when it should for "os.posixpath" during the import
of the os module.

Two fixes are possible:

(1) Change

newmod = imp.new_module('generated.testmodule')

to, e. g.

newmod = imp.new_module('generated_testmodule')
(2) Create a dummy "generated" module and insert it into sys.modules:

import imp, sys

source="""
print 'importing random'
import random
print 'importing os'
import os
print 'bye!'

def getName():
return 'Hello there'
"""

sys.modules["generated"] = imp.new_module("generated")

newmod = imp.new_module('generated.testmodule')
code=compile(source,'<generated code>','exec')
print 'got code...'
exec code in newmod.__dict__
print 'done, newmod.getname(): ',newmod.getName()

While this works, a helpful error message would be nice when an intermediate
package is not found. Unfortunately I was not able to track down the actual
point of failure yet.

Peter
Jul 18 '05 #3
Michael Hudson wrote:
What's going on? Why can't it find os.path?

Dunno. Two things to try:

1) using new.module instead of the imp function


Tried it, no difference. I think they are equivalent.
2) run python -v


A relevant piece of the trace is found below, using
the same code that I posted before. I've done this already
but couldn't find anything that helps me understand why
os.path cannot be imported.
--Irmen
[.... partial 'python -v dynimport.py' output....]
got code...
importing random
# /usr/local/lib/python2.3/random.pyc matches
/usr/local/lib/python2.3/random.py
import generated.random # precompiled from
/usr/local/lib/python2.3/random.pyc
dlopen("/usr/local/lib/python2.3/lib-dynload/math.so", 2);
import generated.math # dynamically loaded from
/usr/local/lib/python2.3/lib-dynload/math.so
dlopen("/usr/local/lib/python2.3/lib-dynload/_random.so", 2);
import generated._random # dynamically loaded from
/usr/local/lib/python2.3/lib-dynload/_random.so
dlopen("/usr/local/lib/python2.3/lib-dynload/time.so", 2);
import generated.time # dynamically loaded from
/usr/local/lib/python2.3/lib-dynload/time.so
importing os
# /usr/local/lib/python2.3/os.pyc matches /usr/local/lib/python2.3/os.py
import generated.os # precompiled from /usr/local/lib/python2.3/os.pyc
import sys # previously loaded (sys)
import posix # previously loaded (posix)
import posix # previously loaded (posix)
# /usr/local/lib/python2.3/posixpath.pyc matches
/usr/local/lib/python2.3/posixpath.py
import generated.posixpath # precompiled from
/usr/local/lib/python2.3/posixpath.pyc
import sys # previously loaded (sys)
# /usr/local/lib/python2.3/stat.pyc matches /usr/local/lib/python2.3/stat.py
import generated.stat # precompiled from /usr/local/lib/python2.3/stat.pyc
import posix # previously loaded (posix)
Traceback (most recent call last):
File "dynimport.py", line 18, in ?
exec code in newmod.__dict__
File "<generated code>", line 5, in ?
File "/usr/local/lib/python2.3/os.py", line 131, in ?
from os.path import curdir, pardir, sep, pathsep, defpath, extsep,
altsep
ImportError: No module named path
# clear __builtin__._
# clear sys.path
# clear sys.argv

[.... end snipped...]

Jul 18 '05 #4
Peter Otten wrote:

Python gets confused by the module name "generated.testmodule", when
a "generated" package does not exist; it seems to look for
"generated.posixpath" when it should for "os.posixpath" during the import
of the os module.
Terrific, that was the problem! Thanks a lot Peter!
After changing the module name to 'generated_testmodule' as you
suggested, it works :-)
Perhaps a more structural improvement is possible but I'm happy
with just changing my generated module name to a name that is
not in a (non-existing) package.
While this works, a helpful error message would be nice when an intermediate
package is not found.


Indeed...

--Irmen de Jong.

Jul 18 '05 #5

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

Similar topics

1
by: Jacek Generowicz | last post by:
I am using a Python program to generate the C++ source code of an extension module in a package which is managed by distutils. What's the best way to instruct distutils to re-generate the code...
3
by: Loi | last post by:
Hi All, I use Bulk insert to put data to myTable. When the SQL server is in local machin, it works well. But when I put the data in a sql server situated not locally, then I get a error message...
2
by: flupke | last post by:
Hi, i have a program with is built like this: startup.py dir1/__init__.py dir1/file1.py dir2/__init__.py dir2/file2.py dir3/__init__.py dir3/file3.py
7
by: Studio P.M. | last post by:
Dear colleagues, Does anyone have an idea where I could find precise and detailed explanation of each and every statement of the following “Web Form Designer generated code”: #region Web...
3
by: pmclinn | last post by:
In version 2003 of visual studio you could see the vs form code. In vs2005 I do not see it. How do I fix this issue?
6
by: Nathan Sokalski | last post by:
I recently converted some ASP.NET 1.1 projects of mine, created with Visual Studio .NET 2003, to Web Application Projects in Visual Studio .NET 2005 so that I could use ASP.NET 2.0 (All my ASP.NET...
0
by: nomoremisterfatguy | last post by:
I generated a class file by using wsdl.exe and a wsdl-file. Now one of the top elements in the result xml is optional which gives me some problems. In the generated code I have this: ...
8
by: Nigel Rantor | last post by:
Hi all, Python newbie here with what I hope is a blindingly obvious question that I simply can't find the answer for in the documentation. So, if I have a tool that generates python code for...
0
by: =?ISO-8859-1?Q?Jan_Thom=E4?= | last post by:
Hi, I've been trying like a madman to make my WSDL work with .net, but it seems I am out of luck. Whenever I add a service reference to Visual C#, the code gets generated fine, however all...
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:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
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...
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
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
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...
0
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...

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.