Question

I've written a simple shell-like program that uses readline in order to provide smart completion of arguments. I would like the mechanism to support arguments that have spaces and are quoted to signify as one argument (as with providing the shell with such).

I've seen that shlex.split() knows how to parse quoted arguments, but in case a user wants to complete mid-typing it fails (for example: 'complete "Hello ' would cause an exception to be thrown when passed to shlex, because of unbalanced quotes).

Is there code for doing this?

Thanks!

Was it helpful?

Solution

I don't know of any existing code for the task, but if I were to do this I'd catch the exception, try adding a fake trailing quote, and see how shlex.split does with the string thus modified.

OTHER TIPS

GNU Readline allows for that scenario with the variable rl_completer_quote_characters. Unfortunatelly, Python does not export that option on the standard library's readline module (even on 3.7.1, the latest as of this writing).

I found a way of doing that with ctypes, though:

import ctypes

libreadline = ctypes.CDLL ("libreadline.so.6")
rl_completer_quote_characters = ctypes.c_char_p.in_dll (
    libreadline, 
    "rl_completer_quote_characters"
)
rl_completer_quote_characters.value = '"'

Note this is clearly not portable (possibly even between Linux distros, as the libreadline version is hardcoded, but I didn't have plain libreadline.so on my computer), so you may have to adapt it for your environment.

Also, in my case, I set only double quotes as special for the completion feature, as that was my use case.

References

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top