Corectly convert from %PATH%=c:\\X; "c:\\a; b" TO ['c:\\X', 'c:\\a; b']
chirayuk
chirayuk at gmail.com
Sun Apr 3 05:22:51 EDT 2005
Michael Spencer wrote:
> chirayuk wrote:
> > Hi,
> >
> > I am trying to treat an environment variable as a python list - and
I'm
> > sure there must be a standard and simple way to do so. I know that
the
> > interpreter itself must use it (to process $PATH / %PATH%, etc) but
I
> > am not able to find a simple function to do so.
> >
> > os.environ['PATH'].split(os.sep) is wrong on Windows for the case
when
> > PATH="c:\\A;B";c:\\D;
> > where there is a ';' embedded in the quoted path.
> >
> > Does anyone know of a simple way (addons ok) which would do it in a
> > cross platform way? If not - I will roll my own. My search has
shown
> > that generally people just use the simple split menthod as above
and
> > leave it there but it seemed like such a common operation that I
> > believe there must be a way out for it which I am not seeing.
> >
> > Thanks,
> > Chirayu.
> >
> You may be able to bend the csv module to your purpose:
>
>
> >>> test = """\"c:\\A;B";c:\\D;"""
> >>> test1 = os.environ['PATH']
> >>> import csv
> >>> class path(csv.excel):
> ... delimiter = ';'
> ... quotechar = '"'
> ...
> >>> csv.reader([test],path).next()
> ['c:\\A;B', 'c:\\D', '']
> >>> csv.reader([test1],path).next()
> ['C:\\WINDOWS\\system32', 'C:\\WINDOWS',
'C:\\WINDOWS\\System32\\Wbem',
> 'C:\\Program Files\\ATI Technologies\\ATI Control Panel',
> 'C:\\PROGRA~1\\ATT\\Graphviz\\bin',
'C:\\PROGRA~1\\ATT\\Graphviz\\bin\\tools',
> 'C:\\WINDOWS\\system32', 'C:\\WINDOWS',
'C:\\WINDOWS\\System32\\Wbem',
> 'C:\\Program Files\\ATI Technologies\\ATI Control Panel',
> 'C:\\PROGRA~1\\ATT\\Graphviz\\bin',
'C:\\PROGRA~1\\ATT\\Graphviz\\bin\\tools',
> 'c:\\python24', 'c:\\python24\\scripts',
'G:\\cabs\\python\\pypy\\py\\bin']
> >>>
>
> HTH
> Michael
That is a cool use of the csv module.
However, I just realized that the following is also a valid PATH in
windows.
PATH=c:\A"\B;C"\D;c:\program files\xyz"
(The quotes do not need to cover the entire path)
So here is my handcrafted solution.
def WinPathList_to_PyList (pathList):
pIter = iter(pathList.split(';'))
OddNumOfQuotes = lambda x: x.count('"') % 2 == 1
def Accumulate (p):
bAcc, acc = OddNumOfQuotes(p), [p]
while bAcc:
p = pIter.next ()
acc.append (p)
bAcc = not OddNumOfQuotes (p)
return "".join (acc).replace('"','')
return [q for q in [Accumulate (p) for p in pIter] if q]
So now I need to check if the os is windows.
Wishful thinking: It would be nice if something like this (taking care
of the cases for other OS's) made it into the standard library - the
interpreter must already be doing it.
Thanks,
Chirayu.
More information about the Python-list
mailing list