line to argv transformation

Chris Angelico rosuav at gmail.com
Mon Jun 16 07:25:50 EDT 2014


On Mon, Jun 16, 2014 at 8:59 PM, Marko Rauhamaa <marko at pacujo.net> wrote:
> Chris Angelico <rosuav at gmail.com>:
>
>> def shell_split(cmd):
>>     return subprocess.check_output("""python -c 'import sys;
>> print("\\0".join(sys.argv[1:]))' """+cmd,shell=True)[:-1].split(b"\0")
>>
>> You'll get back a list of byte strings, in any case. Feel free to pass
>> them through a decode operation, or to incorporate a .decode() into
>> the above stream, as you wish.
>
> Now you are subject to the quirks of /bin/sh. For example, '*.xyz'
> expands itself ('*.xyz') if there is no match in the current working
> directory.
>
> Moreover, you need to guard against arguments like
>
>    $(cat ~/.ssh/id_dsa)
>
> which would spill the beans.

As I said in response to Tim, the somewhat underspecified question
does leave open followups of whether both of those would be features,
rather than bugs. For instance, if "*.py" should expand to a list of
all files matching that glob, should "[123].py" expand to any files
matching that pattern? I'm not sure that your typical glob function
handles that. And should "spam{eggs,spam}" become
"spameggs","spamspam"? (Though that one's bash-specific, I believe.)
Where do you draw the line?

My reading is that it should be one of two options:

1) Split, according to shell rules, and then glob. Nothing more. No
square brackets (probably), no braces, nothing.
2) Do exactly what $CHELL would do, for some value of $CHELL.

But neither is quite clear, and I can see exactly why there isn't
anything in the stdlib. And what shell do you want to imitate, for
option 2? Using /bin/sh makes a lot of sense... but so does /bin/bash.
Or maybe you should use the user's own login shell, if you're wrapping
a command prompt in some way. Perhaps you want to use GLaDOS; but
remember that although fun and learning are the primary goals of this
activity, serious injuries may occur, especially when using backticks
or $( ) in the command.

OP needs to specify better. Otherwise Black Mesa will get the contract.

ChrisA



More information about the Python-list mailing list