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.

Example:

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

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

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

print(O)

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

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

Notes

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