473,722 Members | 2,244 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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>m ain.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.nor mpath(dir)))
module_name, ext = os.path.splitex t(script)
my_script = __import__(modu le_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 2157
In main.py, execfile("gen.p y")

or

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

or

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

or

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

Jeff

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

iD8DBQFC4UtJJd0 1MZaTXX0RAof0AJ 9XXxAeMIANlBdMO XYX/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.p y")

or

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

or

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

or

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

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.p y")

or

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

or

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

or

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

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.pytho n:
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.parseFil e(f)
#
other.func()
print common.d

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

def func():
print common.a
print common.b
for i in range(len(commo n.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_para ms = {} #######
common.env_para ms['EDITOR'] = "foo" #######

def import_libs(dir , script):
""" Imports python script"""
sys.path.insert (0,(os.path.nor mpath(dir)))
module_name, ext = os.path.splitex t(script)
my_script = __import__(modu le_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_para ms ############
# 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.netc om.com | Wulfraed Dennis Lee Bieber KD6MOG <
wu******@dm.net | Bestiaria Support Staff <
=============== =============== =============== =============== == <
Home Page: <http://www.dm.net/~wulfraed/> <
Overflow Page: <http://wlfraed.home.ne tcom.com/> <

Jul 23 '05 #6

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

Similar topics

18
3046
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 a single collections type, I should be proposing a new "namespaces" module instead. Some of my reasons: (1) Namespace is feeling less and less like a collection to me. Even though it's still intended as a data-only structure, the use cases...
9
1630
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
2530
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 Fortran and trying to do it in Python. I got it to work, but now I'm trying to modularize it. My fortran program uses a subroutine and I was trying to do the same thing in Python. But I'm still new so I'm having trouble understanding what I'm...
5
2246
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 possible? Note that both the namespaces should be in the same schema and same xsd file. Could somebody provide a small snippet on how to do this? Thanks for your time.
7
1437
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 unable to access the class from the first without qualifying it, which is what i want to avoid. Any ideas what I am doing wrong? I am attaching the code and compiler error below to show exactly what I am trying to do,
17
2072
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 write a signature for the developer and after getting a good start developing a 2.0 application I thought I should go through the code and start marking classes and with namespaces. I keep getting the following 'missing' error even when using a first...
3
5853
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. On the client side, threads are used to wait on the results of requests to the server. So the question is: how thread-safe is python xmlrpc? If the client makes a request of the server by calling:
9
1386
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 yellow, etc. But in C# Color is not in Drawing! Where is it? Are there any docs on differences in the namespaces? Thanks,
6
1720
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 System.Collections at the Project level and the user calls a page that does not use that namespace, is that wasting
0
8860
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
9376
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8028
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...
1
6678
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5994
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
4501
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 last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4762
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3207
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2146
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.