473,602 Members | 2,872 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

compiling module from string and put into namespace

Hi,

I want to create a function that preprocesses a file and then imports
the parsed file.

What I found out is that you can do something like this:

def ImportFile(file Name):
parsedCode = Parser(fileName ).Parse()
module = new.module(name )
exec parsedCode in module.__dict__
sys.modules[name] = module
import name

But this works only if the ImportFile isnt loaded from a module.
Since the import is local.

So this wouldnt work:

from XXX import ImportFile

ImportFile(file Name)
fileName.Functi on()

Since the import in ImportFile isnt visible the module that calls it.
So how do I do so that the import is visible from callers namespace?

Best regards,

T

May 12 '06 #1
8 1085
glomde wrote:
Hi,

I want to create a function that preprocesses a file and then imports
the parsed file.

What I found out is that you can do something like this:

def ImportFile(file Name):
parsedCode = Parser(fileName ).Parse()
module = new.module(name )
exec parsedCode in module.__dict__
sys.modules[name] = module
import name

But this works only if the ImportFile isnt loaded from a module.
Since the import is local.


Look for __import__() (it's in the builtins) and sys.modules.

--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom. gro'.split('@')])"
May 12 '06 #2
Tanks but that isn't what I am looking for.
I really want a function that you can call and imports
the module into the calling functions namespace.

I dont want the caller to call import but a function.

May 12 '06 #3
glomde wrote:
Tanks but that isn't what I am looking for.
I really want a function that you can call and imports
the module into the calling functions namespace.

I dont want the caller to call import but a function.


come again?
type (__builtins__._ _import__)

<type 'builtin_functi on_or_method'>
--
Edward Elliott
UC Berkeley School of Law (Boalt Hall)
complangpython at eddeye dot net
May 12 '06 #4
glomde a écrit :
Tanks but that isn't what I am looking for.
I really want a function that you can call and imports
the module into the calling functions namespace.
Please read the documentation of the __import__() *function*. (notice
the double leading and ending underscores and the parenthesis).
I dont want the caller to call import but a function.


Please read the documentation of the __import__() *function*. (notice
the double leading and ending underscores and the parenthesis).

May 13 '06 #5
> I dont want the caller to call import but a function.

come again?
type (__builtins__._ _import__)


<type 'builtin_functi on_or_method'>

I didnt mean that __import__ isnt a function, but that I want to
make a function called ImoprtFile that actually does something
very similar that what __import__.

So to rephrsase the questin how does __import__ load a module
into the callers namespace.

Example:

file1

def ImportFile(file Name):
parsedCode = Parser(fileName ).Parse()
module = new.module(name )
exec parsedCode in module.__dict__
sys.modules[name] = module
import name #!!!!!!! This doesn't work. Imports in file1
namespace!!!!!

file2

import file1

file1.ImportFil e(fileName)
fileName.functi on() #This wont work because the import happened
locally in file1!!!!!!!!!! !!!

Now the import in file1 doesnt take effect in file2. So what do I have
to
do to make that work. And I dont want to do a custom hook to import.
So how does __import__ do?

May 13 '06 #6
Ok, now I think I know what I need to do.
I need to create a variable in the calling functions locals.
So how do I get access to the calles locals dictionary?
Is it possible?

May 13 '06 #7
glomde wrote:
I didnt mean that __import__ isnt a function, but that I want to
make a function called ImoprtFile that actually does something
very similar that what __import__.

So to rephrsase the questin how does __import__ load a module
into the callers namespace.


Ok got it now. I'm sure it's doable but it sounds tricky. Wouldn't it be
easier to just have your function return a list of modules to the caller
and have the caller import them?

--
Edward Elliott
UC Berkeley School of Law (Boalt Hall)
complangpython at eddeye dot net
May 13 '06 #8

glomde wrote:
Ok, now I think I know what I need to do.
I need to create a variable in the calling functions locals.
So how do I get access to the calles locals dictionary?
Is it possible?


If your import is used in the current namespace, just use the global
keyword.

Best is if your function just returns the module though, and then you
have bound your name to it exactly as if you had used import.

If you *really* want to poke it into the globals of whereever your
function is called from, you can use :

sys._getframe(1 ).globals['name'] = name

(or something like that, you will need to look up the semantics.)

This is a hack really though, just return the module object and bind
the right name to it where you call it from.

Fuzzyman
http://www.voidspace.org.uk/python/index.shtml

May 13 '06 #9

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

Similar topics

16
10077
by: Jeff Wagner | last post by:
Is there a Python module or method that can convert between numeric bases? Specifically, I need to convert between Hex, Decimal and Binary such as 5Ah = 90d = 01011010b. I searched many places but couldn't find a Python specific one. Thanks, Jeff
14
1748
by: Luc Mazardo | last post by:
The following code works with g++ 2.75 but i've some troubles with compiling with g++ 3.0. Thanks in advance if you have a solution. Here is the error message. main.hpp:28: specializing `struct std::hash<std::string>' in different namespace /usr/include/g++-v3/ext/stl_hash_fun.h:68: from definition of `template<class
0
3048
by: David W. Fenton | last post by:
Today I was working on a hideous old app that I created a long time ago that does a lot of showing/hiding/resizing of fields on one of the forms. I had used constants to store reference values for many of the top/height/left settings. I noticed that some of the constants were defined by using other constant values, and I was impressed that VBA could do that. Here's an example: Const row1Top = 1.0208 * 1440 ' top of first row Const...
4
11333
by: Aaron Queenan | last post by:
When I build a C++ library to .NET using the managed C++ compiler, I get the following error message: Linking... LINK : error LNK2020: unresolved token (0A000005) _CrtDbgReport LINK : error LNK2020: unresolved token (0A000007) memset LINK : error LNK2020: unresolved token (0A000008) free LINK : error LNK2020: unresolved token (0A00000A) atexit LINK : error LNK2020: unresolved token (0A000028) wcscpy LINK : error LNK2020: unresolved...
0
1451
by: phoolimin | last post by:
Dear all, I am trying to embed python into another scripting language, to do this I need to solve a number of problems on importing or compiling python script. First let me state what exactly I want to do, that is, I want the following syntax to be supported in the host language which I am developing: ###################################################### # scripts in the host language
3
1583
by: Mitko Haralanov | last post by:
For various reason, what I need to do is be able to send some Python code (mostly entire functions in the form of a string) to a remote server (written in Python), have that server compile the code and insert it in the local namespace so it is available to be called at a later time. I have gotten the sending and receiving part already written and that works. However, I can't get the compiling part! I have looked at the compile module...
1
1661
by: CeciMar | last post by:
I'm new to vb.net and I have a very simple console application. When I attempt to compile it at the command prompt I get error BC30420 Sub Main not found. I know the namespace and module name but that does not seem to work. Here is my code: Imports System Module Hello Sub Main() Dim Today As Date
0
1037
by: Gabriel Genellina | last post by:
En Sat, 12 Jul 2008 16:15:36 -0300, Akathorn Greyhat <akathorn@gmail.com> escribi�: Welcome! You have to pass in the namespace of the desired module - instead of globals. I'd use an explicit argument:
6
2253
by: msb_6 | last post by:
Currently I have a PHP extension thats all written and compiles under windows, but the PC I'm going to end up putting it on is running Ubuntu 8.04 (g++ 4.2.3). I've delved into PHP documentation and ended up with a simple config.m4 file and the process to compile. However when I try to compile I get loads of errors that I didn't get when compiling under windows. I've managed to simplify the code down and create a simple extension (that...
0
7993
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
7921
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8404
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8270
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6730
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5440
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
3944
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1511
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1256
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 can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.