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

Question about namespaces and import. How to avoid calling os.system

Hi there,

I have two scripts. The first "main.py" sets some variables
and then imports another called "gen.py". The idea is to
provide "main.py" that defines some paths, variables etc.
without using Windows environment variables. Various other "hackers"
will make additional Python scripts (subroutines) like "gen.py"
that utilize variables set by the "main.py" and which "main.py" calls.
I can do this with "subprocess" module by setting its env -variable
but I try to avoid calling shell. How can I merge temporary
the namespaces of the two modules?

----- example run STARTS ---
c:\home\pekka>main.py

imported module: <module 'gen' from 'c:\home\gen.py'>
{'todir': 'c:\\'}
Traceback (most recent call last):
File "C:\home\pekka\main.py", line 16, in ?
gencmd.run_gen()
File "c:\home\gen.py", line 7, in run_gen
print env_params # HOW MAKE THIS DICTIONARY FROM main.py VISIBLE
NameError: global name 'env_params' is not defined

----- example run STOPS ---

---- main.py STARTS ----
import os, sys
env_params = {}
env_params['EDITOR'] = "foo"

def import_libs(dir, script):
""" Imports python script"""
sys.path.insert(0,(os.path.normpath(dir)))
module_name, ext = os.path.splitext(script)
my_script = __import__(module_name)
print "\nimported module: %s" % (my_script)
del sys.path[0]
return my_script

if __name__ == "__main__":
gencmd = import_libs("c:\home", "gen.py")
gencmd.run_gen()

---main.py ENDS -----

---- gen.py STARTS ----
# Store this script to directory c:\home"
my_env_params ={}
my_env_params['todir'] = "c:\\"

def run_gen():
# Get commandline arguments
print my_env_params
print env_params # HOW MAKE THIS DICTIONARY FROM main.py VISIBLE

if __name__ == "__main__":
run_gen()

---gen.py ENDS -----
-pekka-
Jul 22 '05 #1
5 2135
In main.py, execfile("gen.py")

or

In gen.py, have something like
from __main__ import env_params

or

In main.py, have something like
import __builtins__; __builtins__.env_params = env_params

or

call a function in the gen.py with env_params as a parameter
import gen
gen.do(env_params)

Jeff

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.1 (GNU/Linux)

iD8DBQFC4UtJJd01MZaTXX0RAof0AJ9XXxAeMIANlBdMOXYX/guMDYuPAACgnc8P
SX5bkxWZc8Kk/o6Fphx49zk=
=HcTB
-----END PGP SIGNATURE-----

Jul 22 '05 #2
Thanks,

I will analyse these 4 options and select the most suitable
since there are other issues involved too, like
"the "main.py" reads contents of a file to a list that gets
passed to the "gen.py" with dictionary "env_params"".
I try to avoid parsing the contents of the file both
in "main.py" and in "gen.py"

-pekka-
Jeff Epler wrote: In main.py, execfile("gen.py")

or

In gen.py, have something like
from __main__ import env_params

or

In main.py, have something like
import __builtins__; __builtins__.env_params = env_params

or

call a function in the gen.py with env_params as a parameter
import gen
gen.do(env_params)

Jeff

Jul 22 '05 #3
Thanks,

I will analyse these 4 options and select the most suitable
since there are other issues involved too, like
"the "main.py" reads contents of a file to a list that gets
passed to the "gen.py" with dictionary "env_params"".
I try to avoid parsing the contents of the file both
in "main.py" and in "gen.py"

-pekka-
Jeff Epler wrote: In main.py, execfile("gen.py")

or

In gen.py, have something like
from __main__ import env_params

or

In main.py, have something like
import __builtins__; __builtins__.env_params = env_params

or

call a function in the gen.py with env_params as a parameter
import gen
gen.do(env_params)

Jeff

Jul 22 '05 #4
>>>>> "PN" == Pekka Niiranen <pe************@wlanmail.com> writes:

PN> Hi there,
PN> I have two scripts. The first "main.py" sets some variables
PN> and then imports another called "gen.py". The idea is to
PN> provide "main.py" that defines some paths, variables etc.
PN> without using Windows environment variables. Various other "hackers"
PN> will make additional Python scripts (subroutines) like "gen.py"
PN> that utilize variables set by the "main.py" and which "main.py" calls.
PN> I can do this with "subprocess" module by setting its env -variable
PN> but I try to avoid calling shell. How can I merge temporary
PN> the namespaces of the two modules?

The built-in execfile should do the trick.

--
Patricia J. Hawkins
Hawkins Internet Applications
www.hawkinsia.com
Jul 23 '05 #5
On Fri, 22 Jul 2005 22:24:18 +0300, Pekka Niiranen
<pe************@wlanmail.com> declaimed the following in
comp.lang.python:
Hi there,

I have two scripts. The first "main.py" sets some variables
and then imports another called "gen.py". The idea is to
provide "main.py" that defines some paths, variables etc.
without using Windows environment variables. Various other "hackers"
will make additional Python scripts (subroutines) like "gen.py"
that utilize variables set by the "main.py" and which "main.py" calls.
I can do this with "subprocess" module by setting its env -variable
but I try to avoid calling shell. How can I merge temporary
the namespaces of the two modules?
Normally, I'd say that is setting the namespaces upside down...
That is, that the "main" program has access to the namespaces of those
that modules that /it/ imports (and they can access the namespace of
those they import), but imported modules can only access stuff
explicitly passed to them from the main/parent module.

If your main is being used to parse out some data file, and you
then want the parsed data available in randomly imported modules... I'd
make a separate module just for the parser AND parsed data.

In pseudo-code
-=-=-=-=-=-=-=-=-=-
#common.py

a = None
b = None
c = []
d = {}
#etc

def parseFile(fin):
global a, b, c, d
ln = fin.readline()
# do whatever needs to be done to parse the line
# "assigning" the result to a..d whatever

-=-=-=-=-=-=-=-=-=-
#main.py

import common
import other

f = open("data.file", "r")
common.parseFile(f)
#
other.func()
print common.d

-=-=-=-=-=-=-=-=-=-
#other.py
import common

def func():
print common.a
print common.b
for i in range(len(common.c)):
common.d[i] = common.c[i]

-=-=-=-=-=-=-=-=-=-=-

DO NOT use
from common import *
since you want all modules to reference the /same/ "common" namespace.

Or, to use your example code (modified).

-=-=-=-=-=-=-=-=-
#common.py
pass # Basically just an empty module for the creation of a namespace

---- main.py STARTS ----
import os, sys

import common #############

common.env_params = {} #######
common.env_params['EDITOR'] = "foo" #######

def import_libs(dir, script):
""" Imports python script"""
sys.path.insert(0,(os.path.normpath(dir)))
module_name, ext = os.path.splitext(script)
my_script = __import__(module_name)
print "\nimported module: %s" % (my_script)
del sys.path[0]
return my_script

if __name__ == "__main__":
gencmd = import_libs("c:\home", "gen.py")
gencmd.run_gen()

---main.py ENDS -----

---- gen.py STARTS ----
# Store this script to directory c:\home"

import common #########

my_env_params ={}
my_env_params['todir'] = "c:\\"

def run_gen():
# Get commandline arguments
print my_env_params
print common.env_params ############
# HOW MAKE THIS DICTIONARY FROM main.py VISIBLE

if __name__ == "__main__":
run_gen()

---gen.py ENDS -----

Should be all that is needed (Please note, I did not TRY this)
-- ================================================== ============ <
wl*****@ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG <
wu******@dm.net | Bestiaria Support Staff <
================================================== ============ <
Home Page: <http://www.dm.net/~wulfraed/> <
Overflow Page: <http://wlfraed.home.netcom.com/> <

Jul 23 '05 #6

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

Similar topics

18
by: Steven Bethard | last post by:
In the "empty classes as c structs?" thread, we've been talking in some detail about my proposed "generic objects" PEP. Based on a number of suggestions, I'm thinking more and more that instead of...
9
by: Sean | last post by:
Is there any way I could have the following work? First I would have a module define a function to do something like print some data. ----- module_name.py ----- def print_this(data):
32
by: David | last post by:
Hi I'm trying to teach myself python and so far to good, but I'm having a bit of trouble getting a function to work the way I think it should work. Right now I'm taking a simple program I wrote in...
5
by: Zombie | last post by:
Hi, Can I have 2 namespaces in the same XML schema? In the schema, I wish to declare elements such that some of them belong to one namespace and others belong to a second namespace. Is this...
7
by: Aniket Sule | last post by:
Hi, I am trying to use a class from one namespace in another via the using directive. The 2 namespaces have some part of the name in common (A.B.x, A.B.y). However in the second namespace, I am...
17
by: clintonG | last post by:
Using 2.0 with Master Pages and a GlobalBaseClass for the content pages. I understand the easy part -- the hierarchical structure of a namespace naming convention -- but the 2.0 IDE does not...
3
by: David Hirschfield | last post by:
An xmlrpc client/server app I'm writing used to be super-simple, but now threading has gotten into the mix. On the server side, threads are used to process requests from a queue as they come in....
9
by: Tina | last post by:
As I continue to convert a large vb.net project to C# is am now seeing that the namespaces are different. I never expected this. For instance in vb I use System.Drawing.Color so I can say red ...
6
by: =?Utf-8?B?TUNN?= | last post by:
What is the difference between importing a namespace at the: 1. Project level 2. web.config level 3. Page level What are the requirements/benefits of each? If I import a namespace such as...
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
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
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
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
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...

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.