[issue13238] Add shell command helpers to shutil module

Nick Coghlan report at bugs.python.org
Sat Oct 22 02:20:35 CEST 2011


Nick Coghlan <ncoghlan at gmail.com> added the comment:

It's a flow thing. This idea was kicked off by the process of translating a large Perl script to Python and paying attention to what the translation made *worse*.

One of the big things it made worse was the translation of "qx" (quoted executable) strings. In Perl, those are almost as neat and tidy as if you were writing directly in the shell:

    qx|ls -l $dirname|

The thought process isn't "build this command and then execute it", it's "run this shell command".

Yes, you have to be careful that "dirname" is legal in the shell, but that usually isn't a big problem in practice, because dirname came from a previous listdir call, or you otherwise know that it's valid to interpolate it into the command (and if it isn't, then the bug lies in the way 'dirname' was populated, not in this operation).

Now, Python's never going to have implicit string interpolation, and that's fine - we have explicit interpolation instead. A direct translation of the above to idiomatic Python 2.7 code looks like the following:

    subprocess.check_output("ls -l {}".format(dirname), shell=True)

Now, if I'm doing system administration tasks (like the script I was translating), then I'm going to be doing that kind of thing a *lot*. I'm also likely to be a sysadmin rather than a programmer, so rather than going "Oh, I can write a helper function for this", my natural reaction is going to be "I'm going to use a language that doesn't get in my way so much".

This proposal is aimed directly at making Python a better language for systems administration by making shell invocation almost as easy as it is in Perl:

    shutil.check_shell_output("ls -l {}", dirname)

Heck, if someone really wanted to, they could even do:

    qx = shutil.check_shell_output
    qx("ls -l {}", dirname)

However, this is also why I *don't* want these methods in subprocess - they put the burden on the user to think about their data as if they were writing shell scripts, because that data is going to get passed straight to the shell for execution without any additional escaping. That's a reasonable idea for a shell utility in shutil, it's not reasonable for a general purpose subprocess manipulation utility in subprocess.

----------

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue13238>
_______________________________________


More information about the Python-bugs-list mailing list