brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: Python's shlex.split and shlex.quote handle shell quoting for you

Python
~/tips/tip-python-shlex-split-quote

import shlex

Split a command line like the shell does, and quote values safely for one.

Splitting a command on spaces breaks as soon as a file name has a space in it. The shlex module knows the shell’s quoting rules, in both directions.

import shlex

print(shlex.split('scp "my file.txt" host:/tmp'))
# ['scp', 'my file.txt', 'host:/tmp']

print(shlex.quote("my file; rm x"))
# 'my file; rm x'   (quoted, so the ; is harmless)

print(shlex.join(["ls", "-l", "a b"]))
# ls -l 'a b'

split turns a string the way you’d type it into a list you can pass to subprocess.run. It is the one for a command that comes from a config file. quote wraps a single value so the shell sees it as one word, and join does that for a whole list, which is perfect for logging the exact command you’re about to run so you can paste it into a terminal.

The safest option is still to skip the shell entirely and pass a list to subprocess.run without shell=True. I’d reach for quote only when you really need a shell string, for example a command that runs over SSH or ends up in a generated script.

It follows POSIX shell rules only. The docs say plainly that it isn’t meant for Windows cmd.exe or PowerShell, so don’t rely on it there.

Further reading: shlex module

More Python tips import asyncio from enum import StrEnum, auto except* ValueError as eg: import pytest pytest --maxfail=2 All Python tips (107) All topics

Link