(Almost) command line simulation with execfile

Stefan Schwarzer s.schwarzer at ndh.net
Fri Dec 28 12:36:40 EST 2001


Hello

I'm trying to make a wrapper class to execute example scripts. For
that, I use

class Example:
    '''Provide demonstration services for Python scripts.'''

    ...

    def execute(self):
        '''Read and execute the example script.'''
        print 'Executing %s ...' % self.filename
        print
        temp_globals = globals().copy()
        temp_locals = {}
        try:
            execfile(self.filename, temp_globals, temp_locals)
        except:
            print "Ooops, there seems to be a problem ..."
            print
            traceback.print_exc(file=sys.stdout)

If it wasn't for catching exceptions in the example scripts caused by
invalid user input, I would use os.system. On the other hand, the
scripts should be simple, so I would not like to put the exception
handling stuff in (every) example script.

My problem is that the above execfile call doesn't behave similar to
os.system if I have import statements in the executed file. In this
case, I get a name error which I do not get with  python file.py
(i. e. executing the example script directly from the command line).

The output of a wrapped script with an  import urllib  statement is

-----
Executing internet.py ...

Please ensure you are connected to the internet and press [Return]:

The first 150 characters from http://www.python.org/:
Ooops, there seems to be a problem ...

Traceback (most recent call last):
  File "wrapper.py", line 80, in execute
    execfile(self.filename, temp_globals, temp_locals)
  File "internet.py", line 50, in ?
    print url_content_part(url, count)
  File "internet.py", line 12, in url_content_part
    fetched = urllib.urlopen(url)
NameError: global name 'urllib' is not defined
-----

Perhaps it's a problem with the globals dictionary? What should I
probably use instead? (Note that, in contrast to other postings I have
found with Google groups, I do _not_ want to have modified the
namespaces of my wrapper module or the class instance.)

Can somebody explain what's going on here and what I should do? :-)
Many thanks in advance!

Stefan



More information about the Python-list mailing list