Return a Windows shell-escaped version of the string *s* that is safe to pass through cmd.exe Handles two interpretation layers: 1. cmd.exe metacharacters - neutralized by double-quoting when the string contains any cmd.exe special characters. 2. MSVC C runtime argv par
(s)
| 353 | |
| 354 | |
| 355 | def _windows_cmd_shell_quote(s): |
| 356 | """Return a Windows shell-escaped version of the string *s* that is |
| 357 | safe to pass through cmd.exe |
| 358 | |
| 359 | Handles two interpretation layers: |
| 360 | 1. cmd.exe metacharacters - neutralized by double-quoting when |
| 361 | the string contains any cmd.exe special characters. |
| 362 | 2. MSVC C runtime argv parsing - backslash/double-quote escaping |
| 363 | so the target process receives the correct argument. |
| 364 | |
| 365 | Note: cmd.exe %VAR% expansion and !VAR! delayed expansion |
| 366 | cannot be reliably escaped inside double quotes on the |
| 367 | command line and are not handled here. |
| 368 | |
| 369 | :param s: A string to escape |
| 370 | :return: An escaped string |
| 371 | """ |
| 372 | if not s: |
| 373 | return '""' |
| 374 | |
| 375 | buff = [] |
| 376 | num_backslashes = 0 |
| 377 | needs_quoting = False |
| 378 | for character in s: |
| 379 | if character == '\\': |
| 380 | num_backslashes += 1 |
| 381 | elif character == '"': |
| 382 | if num_backslashes > 0: |
| 383 | buff.append('\\' * (num_backslashes * 2)) |
| 384 | num_backslashes = 0 |
| 385 | buff.append('\\"') |
| 386 | needs_quoting = True |
| 387 | else: |
| 388 | if num_backslashes > 0: |
| 389 | buff.append('\\' * num_backslashes) |
| 390 | num_backslashes = 0 |
| 391 | if character in _WIN_CMD_UNSAFE_CHARS: |
| 392 | needs_quoting = True |
| 393 | buff.append(character) |
| 394 | |
| 395 | if needs_quoting: |
| 396 | # Trailing backslashes must be doubled when we append a closing |
| 397 | # double quote — without doubling, a trailing backslash would |
| 398 | # escape the closing quote. |
| 399 | if num_backslashes > 0: |
| 400 | buff.append('\\' * (num_backslashes * 2)) |
| 401 | inner = ''.join(buff) |
| 402 | return f'"{inner}"' |
| 403 | |
| 404 | if num_backslashes > 0: |
| 405 | buff.append('\\' * num_backslashes) |
| 406 | return ''.join(buff) |
| 407 | |
| 408 | |
| 409 | def get_popen_kwargs_for_pager_cmd(pager_cmd=None): |
no outgoing calls
no test coverage detected