Python Windows subprocess bugs

For Python on Windows, the following subprocess inputs need to be tweaked for Windows vs. other OS’s:

  • executable name (cannot start with ./ on Windows)
  • pathlib.Path must be cast to str
  • Windows needs shell=True

A simple boilerplate method to handle these issues follows, typically put in __init__.py for your package or other suitable location

#!/usr/bin/env python
import os

EXE = './myprogram'
SHELL = False

if os.name == 'nt':
    EXE = exe[2:]
    SHELL = True
    
def myfunc():

    cmd = [EXE, myparam1, myparam2]

    subprocess.check_call(cmd, cwd=str(myexepath), shell=SHELL)

Tags:

Categories:

Comments

Written by Michael Hirsch, Ph.D. //