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

Pekka Niiranen pekka.niiranen at wlanmail.com
Fri Jul 22 15:24:18 EDT 2005


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-



More information about the Python-list mailing list