473,729 Members | 2,177 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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

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.

Jul 18 '05 #1
5 1760
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\\s ystem32', 'C:\\WINDOWS', 'C:\\WINDOWS\\S ystem32\\Wbem',
'C:\\Program Files\\ATI Technologies\\A TI Control Panel',
'C:\\PROGRA~1\\ ATT\\Graphviz\\ bin', 'C:\\PROGRA~1\\ ATT\\Graphviz\\ bin\\tools',
'C:\\WINDOWS\\s ystem32', 'C:\\WINDOWS', 'C:\\WINDOWS\\S ystem32\\Wbem',
'C:\\Program Files\\ATI Technologies\\A TI Control Panel',
'C:\\PROGRA~1\\ ATT\\Graphviz\\ bin', 'C:\\PROGRA~1\\ ATT\\Graphviz\\ bin\\tools',
'c:\\python24', 'c:\\python24\\ scripts', 'G:\\cabs\\pyth on\\pypy\\py\\b in']


HTH
Michael

Jul 18 '05 #2
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\\s ystem32', 'C:\\WINDOWS',

'C:\\WINDOWS\\S ystem32\\Wbem', 'C:\\Program Files\\ATI Technologies\\A TI Control Panel',
'C:\\PROGRA~1\\ ATT\\Graphviz\\ bin', 'C:\\PROGRA~1\\ ATT\\Graphviz\\ bin\\tools', 'C:\\WINDOWS\\s ystem32', 'C:\\WINDOWS', 'C:\\WINDOWS\\S ystem32\\Wbem', 'C:\\Program Files\\ATI Technologies\\A TI Control Panel',
'C:\\PROGRA~1\\ ATT\\Graphviz\\ bin', 'C:\\PROGRA~1\\ ATT\\Graphviz\\ bin\\tools', 'c:\\python24', 'c:\\python24\\ scripts',

'G:\\cabs\\pyth on\\pypy\\py\\b in']
>>>


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.s plit(';'))
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.

Jul 18 '05 #3
if your goal is to search for files on a windows-style path environment
variable, maybe you don't want to take this approach, but instead wrap
and use the _wsearchenv or _searchenv C library functions
http://msdn.microsoft.com/library/en...wsearchenv.asp

Incidentally, I peeked at the implementation of _searchenv in wine (an
implementation of the win32 API for Unix), and it doesn't do the
quote-processing that you say Windows does. The msdn page doesn't give
the syntax for the variable either, which is pretty typical. Do you
have an "official" page that discusses the syntax?

Jeff

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.6 (GNU/Linux)

iD8DBQFCUAVOJd0 1MZaTXX0RAkr/AJ4mRxmzp1yFPVq 3E0zLaKwcQMOwDg CePo8e
IY+Ee/9janJgX/eezLtlYdc=
=cTMF
-----END PGP SIGNATURE-----

Jul 18 '05 #4
chirayuk wrote:

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)
Too bad! What a crazy format!
So here is my handcrafted solution.

def WinPathList_to_ PyList (pathList):
pIter = iter(pathList.s plit(';'))
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]
Does it work?

I get:
test2 = r'c:\A"\B;C"\D; c:\program files\xyz"'
WinPathList_to_ PyList(test2) Traceback (most recent call last):
File "<input>", line 1, in ?
File "pathsplit" , line 31, in WinPathList_to_ PyList
File "pathsplit" , line 27, in Accumulate
StopIteration
Also, on the old test case, I get: WinPathList_to_ PyList("""\"c:\ \A;B";c:\\D;""" ) ['c:\\AB', 'c:\\D']


Should the ';' within the quotes be removed?

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.

This sort of 'stateful' splitting is a somewhat common task. If you're feeling
creative, you could write itertools.split by(iterable, separator_func)

This would be a sister function to itertools.group by (and possible derive from
its implementation) . separator_func is a callable that returns True if the item
is a separator, False otherwise.

splitby would return an iterator of sub-iterators (like groupby) defined by the
items between split points

You could then implement parsing of crazy source like your PATH variable by
implementing a stateful separator_func

Michael

Jul 18 '05 #5
I do agree that it is a crazy format - and am amazed that it works at
the prompt.

For the first case - you have a mismatched double quote for test2 at
the end of the string. test2 should be r'c:\A"\B;C"\D; c:\program
files\xyz' instead. For the 2nd case - my code swallowed the ';' it
split on - so I need a acc.append (';') just before the acc.append(p)
in Accumulate. The code then works. It needs to be fixed to take care
of extra double quotes and also a missing one (cmd.exe appeats to
assume one at the end if it did not find one.)

The itertools.split by idea sounds really cool. I did not feel like
writing a state machine as the state was so simple to maintain here -
but I'd like to write a splitby so that it makes it easier to do such
crazy splitting in general.

Chirayu.

Jul 18 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
1499
by: mqsash | last post by:
Hi Problem : Unable to deploy an assembly in IE, as a cab file. (Works fine when deployed as a dll ) Description : I have created a assembly (dll with no user interface)in C# which I deploy in IE. The dll name is test.dll and the object tag in the html page is as follows. <OBJECT ID="myAssembly" classid="test.dll#testNS.Class1"></OBJECT>
2
5495
by: mqsash | last post by:
Hi Problem : Unable to deploy an assembly in IE, as a cab file. (Works fine when deployed as a dll ) Description : I have created a assembly (.dll) in C# which I deploy in IE. The dll name is test.dll and the object tag in the html page is as follows. <OBJECT ID="myAssembly"
8
4824
by: Krishnan Margabandhu | last post by:
I'm writing a Pocket PC app that will run when a device is first powered on. I want this program to get some data from the user and invoke a CAB file to install a software on the device. How do I invoke a CAB file from the VB app? Thanks
0
1382
by: Frank | last post by:
I am attempting to convert an asp file to a asp.net file using C#. The original file has an ActiveX control which is contained in a cab file. The cab file contains the .ocx file which connects to a socket and transfers client info to a server, as well as several .dlls The cab file also references another cab file which contains files to install on the client machine in case they do not have VBRuntime6 installed on their machine.
1
5164
by: Frank | last post by:
Short Version of Question: Can anyone provide an example of how I should embed the ActiveX and license, and then use it in a function?
0
2016
by: Kleanthis | last post by:
I have a problem, when deploying multilingual applications using cab files on Compact Framework 2.0. It seems that something is going wrong with compact framework 2.0 Below I have a description of the problem The main Smart Device Application contains 3 resource files under the Properties folder, in order to produce localization satellite asseblies. Those resource files are named Resources.resx (a default empty resource file),...
4
1779
by: Pohihihi | last post by:
Hello NG, I have few assemblies that I want them to be in a cab file while deployed. Those asms are referenced in the program. How can I use cab files while running the program or in other words what should I do so that my program still runs when my distributed assemblies are combined in a cab file? Thx, Po
3
1264
by: Ronald S. Cook | last post by:
I'm reading up on Composite Application UI Block (CAB) and wondering if it is overkill for the enterprise Windows app we plan to build. We simply want a shell app where then each modult that is selected exists within. We could use user controls but we're not crazy about the idea. If you tell me to continue to explore CAB, I will. So, with Windows Presentation Foundation (WPF) out, is that a successor to CAB or totally separate?
2
3317
by: Virgil Stokes | last post by:
I would appreciate python code for creating *.cab files. --V. Stokes
0
8913
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9280
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8144
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6722
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6016
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4525
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4795
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2677
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2162
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.