mslex

1.3.0 · active · verified Mon Apr 13

mslex is a Python library that provides `shlex`-like functionality specifically tailored for Windows shell command-line parsing and quoting. It addresses the complex and often inconsistent behaviors of `cmd.exe`, `CommandLineToArgvW`, and older `msvcrt.dll` runtimes on Windows. The library offers `split`, `quote`, and `join` functions, making it easier to construct and deconstruct command lines for Windows environments. It is currently at version 1.3.0, released on October 16, 2024, and is considered stable and actively maintained for its niche use case.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates the core `mslex.quote` and `mslex.split` functions. It shows how to quote a path with spaces for Windows command lines and how to parse a command string into arguments. A note on complex Windows quoting behavior is included, highlighting mslex's ability to handle nuances and potential ambiguities.

import mslex
import sys

# Example 1: Quoting a string for Windows command line
path_with_spaces = r'C:\Program Files\My App\app.exe'
quoted_path = mslex.quote(path_with_spaces)
print(f"Original path: {path_with_spaces}")
print(f"Quoted path: {quoted_path}")
# Expected: C:\\Program\ Files\\My\ App\\app.exe (or similar depending on for_cmd)

# Example 2: Splitting a Windows command line string
command_string = 'dir "C:\\Program Files" /s'
args = mslex.split(command_string)
print(f"Command string: {command_string}")
print(f"Split arguments: {args}")
# Expected: ['dir', 'C:\\Program Files', '/s']

# Example 3: Handling complex Windows quoting nuances
# mslex attempts to parse both UCRT and msvcrt.dll ways by default and can raise an error if they disagree.
# You can specify ucrt=True/False or like_cmd=True/False for specific behaviors.
# This example demonstrates a basic split without specific runtime flags.
complex_command = 'program.exe arg1 "arg 2 with spaces" ^"escaped arg^"'
if sys.platform == 'win32':
    try:
        parsed_complex_args = mslex.split(complex_command)
        print(f"Complex command (Windows): {complex_command}")
        print(f"Parsed complex arguments: {parsed_complex_args}")
    except ValueError as e:
        print(f"Could not parse complex command due to ambiguity: {e}")
else:
    print(f"mslex is primarily for Windows; skipping complex example on {sys.platform}")

view raw JSON →