[Tutor] 'source' in python or preloading variables

John washakie at gmail.com
Sat Oct 27 19:57:44 CEST 2007


Thanks,

it's strange, it works within a script defined at the top, but if I try to
import it from a module it fails:

NameError: name 'files' is not defined



On 10/27/07, Aditya Lal <aditya.n.lal at gmail.com> wrote:
>
>
>
> On 10/27/07, John <washakie at gmail.com> wrote:
> >
> > Note, i need the ns+1 because the 'source files are not zero indexed.
> >
> > On 10/27/07, John <washakie at gmail.com > wrote:
> > >
> > > Here's where I am:
> > >
> > >
> > > def source(filename, vList):
> > >  """ takes a file object and a list of variables as input """
> > >  import re
> > >  # Read the file
> > >  fid=open(filename,'r')
> > >  lines = fid.readlines()
> > >  fid.close()
> > >  #how many variables
> > >  ns=len(lines)/len(vList)
> > >  #predefine the varibles
> > >  for v in vList:
> > >   exec( 'global %s ; %s = [0]*(ns+1)' % (v, v))
> > >
> > >  # Make it python friendly: put all values in 'single quotes'
> > >  cmd = '\n'.join([re.sub( r'^([^=]+)=(.*)$', r"\1='\2'", v) for v in
> > > lines])
> > >  exec(cmd)
> > >  for v in vList:
> > >   exec( '%s=%s[1:]' % (v,v))
> > >
> > > source('infile.py',['files','nfiles','nreleases'])
> > >
> > > print files
> > > print nreleases
> > > print nfiles
> > >
> > >
> > >
> > > But oddly, my output is:
> > >
> > > [0, 'ASP_200603', 'ASP_200604', 'ASP_200605']
> > > [0, '248', '240', '248']
> > > [0, '3', '3', '3']
> > >
> > >
> > >
> > > So, I am not properly getting rid of the list[0], is it something with
> > > the 'global' nature of the vairables... it looks like it's only changing
> > > locallly in my source function.
> > >
> >
> >
> >
> > --
> > Configuration
> > ``````````````````````````
> > Plone 2.5.3-final,
> > CMF-1.6.4,
> > Zope (Zope 2.9.7-final, python 2.4.4, linux2),
> > Five 1.4.1,
> > Python 2.4.4 (#1, Jul 3 2007, 22:58:17) [GCC 4.1.1 20070105 (Red Hat
> > 4.1.1-51)],
> > PIL 1.1.6
> >
>
> I think you need to define the variable global again otherwise it will
> re-assign the object in local space.
>
> exec( "global %s ; %s = %s[1:]" % (v,v,v) )
>
> --
> Aditya
>



-- 
Configuration
``````````````````````````
Plone 2.5.3-final,
CMF-1.6.4,
Zope (Zope 2.9.7-final, python 2.4.4, linux2),
Five 1.4.1,
Python 2.4.4 (#1, Jul 3 2007, 22:58:17) [GCC 4.1.1 20070105 (Red Hat
4.1.1-51)],
PIL 1.1.6
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071027/0aa268d0/attachment.htm 


More information about the Tutor mailing list