Corectly convert from %PATH%=c:\\X; "c:\\a; b" TO ['c:\\X', 'c:\\a; b']

Michael Spencer mahs at telcopartners.com
Sat Apr 2 20:18:48 EST 2005


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




More information about the Python-list mailing list