# Mounting and unmounting volumes in Python

I have a few batch scripts running on an ancient Mac Mini here at home, mostly set up in ~/Library/LaunchAgents with the venerable (but still tremendously useful) Lingon.

A few of them check if other machines are on at the time and rsync files to and fro, partly due to my desire for minimal redundancy and partly because there are some things I want to have on hand (like, say, the last 25 kids’ photos that are usually on my office Mac, but which is not always on).

Most of those are in Python, and despite the native bindings I find it somewhat annoying to fool around with the Scripting Bridge to do basic things, so I often go and invoke osascript directly.

The other day I wanted to mount and unmount network drives, and after googling around a bit for a sane way to handle time outs, I put the following together, which might be of use to someone else as well:

def waitfor(command, timeout):
"""call shell-command and either return its output or kill it
if it doesn't normally exit within timeout seconds and return None"""
import subprocess, datetime, os, time, signal
start = datetime.datetime.now()
process = subprocess.Popen(command, shell=True,stdout=subprocess.PIPE, stderr=subprocess.PIPE)
while process.poll() is None:
time.sleep(0.2)
now = datetime.datetime.now()
if (now - start).seconds > timeout:
os.kill(process.pid, signal.SIGKILL)
os.waitpid(-1, os.WNOHANG)
return None