Python pathlib cast to str for subprocess

Python pathlib is part of Python standard library. When using Python subprocess, in general, do str(mypath) where type(mypath) is pathlib.Path.


#!/usr/bin/env python
from pathlib import Path
import subprocess

P = Path('~').expanduser()

O = subprocess.check_output(['dir', str(P)])


if you don’t cast pathlib.Path to str:

TypeError: argument of type ‘WindowsPath’ is not iterable.


You should rarely if ever need shell=True. On Windows in particular, give the full path to a non-system executable.

Related: Idiomatic pathlib Python