[Tutor] shlex parsing
Steven D'Aprano
steve at pearwood.info
Thu Jul 28 02:27:52 CEST 2011
Karim wrote:
>
> Hello All,
>
> I would like to parse this TCL command line with shlex:
>
> '-option1 [get_rule A1 B2] -option2 $VAR -option3 TAG'
>
> And I want to get the splitted list:
>
> ['-option1', '[get_rule A1 B2]', '-option2', '$VAR', '-option3', 'TAG']
>
> Then I will gather in tuple 2 by 2 the arguments.
>
> I tried to the shlec properties attributes 'quotes', 'whitespace', etc...
I don't understand what you are doing here. Please show the code you use.
The shlex module doesn't support bracketed expressions. I recommend you
write a post-processor. Start with doing this:
>>> import shlex
>>> text = '-option1 [get_rule A1 B2] -option2 $VAR -option3 TAG'
>>> shlex.split(text)
['-option1', '[get_rule', 'A1', 'B2]', '-option2', '$VAR', '-option3',
'TAG']
then take that list and reassemble the pieces starting with '[' until
']' Something like this, untested:
def reassemble(items):
result = []
bracketed = False
current = ''
for item in items:
if item.startswith('['):
bracketed = True
if bracketed:
current += item
if item.endswith(']'):
bracketed = False
result.append(current)
current = ''
else:
result.append(item)
return result
> But I make 'choux blanc'.
I don't know what that means.
--
Steven
More information about the Tutor
mailing list