This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: Windows cmd.exe character escaping function
Type: enhancement Stage:
Components: Library (Lib) Versions: Python 3.5
process
Status: open Resolution:
Dependencies: Superseder:
Assigned To: Nosy List: Jim.Jewett, r.david.murray
Priority: normal Keywords:

Created on 2014-06-13 19:10 by Jim.Jewett, last changed 2022-04-11 14:58 by admin.

Messages (2)
msg220483 - (view) Author: Jim Jewett (Jim.Jewett) * (Python triager) Date: 2014-06-13 19:10
Inspired by https://mail.python.org/pipermail/python-dev/2014-June/135029.html and the following thread.  

"""
Normal Windows behavior:

  >hg status --rev ".^1"
  M mercurial\commands.py
  ? pysptest.py

  >hg status --rev .^1
  abort: unknown revision '.1'!

So, ^ is an escape character. See
http://www.tomshardware.co.uk/forum/35565-45-when-special-command-line
"""

It probably isn't possible to pre-escape commands for every possible command interpreter, but it makes sense to get the standard shells right. 

In fact, global function list2cmdline already exists (and is apparently specific to the Microsoft compiler), but ... its rules are not the same as those of the default windows shell.  (Per the tomshardware link, those rules (for windows) did change a while back.)

I propose a similar list2shellcmd function.  Based on my own very incomplete information, it would currently look like:

def list2shellcmd(seq):
    """Turn the sequence of arguments into a single command line, with escaped characters."""
    if mswindows:
        line=list2cmdline(seq).replace("^", "^^")
    else:
        line=" ".join(seq)
    return line

but there may well be escapes (such as \) that are appropriate even for posix.

Note that related issue http://bugs.python.org/issue7839 proposes a larger cleanup, such as forbidding the problematic functionality entirely.
msg220487 - (view) Author: R. David Murray (r.david.murray) * (Python committer) Date: 2014-06-13 19:38
This should instead be an escape function parallel to the shlex.quote function for unix.  I was talking to someone on IRC the other day who had at least a partial implementation, but I guess they haven't opened an issue for it.  (At least, I can't find one.)
History
Date User Action Args
2022-04-11 14:58:04adminsetgithub: 65952
2014-06-13 19:38:56r.david.murraysetnosy: + r.david.murray

messages: + msg220487
title: subprocess shell=True on Windows character escaping -> Windows cmd.exe character escaping function
2014-06-13 19:10:48Jim.Jewettcreate