我正在使用 Python 脚本来装载 OS X 卷。当卷已经挂载(因此脚本无法挂载到本地目录)时,如何防止出现错误?
def volumeMounter(remote_dir, local_dir):
# Create local dir if it does not exist
if not os.path.exists( local_dir ):
os.makedirs( local_dir )
local_dir = os.path.abspath(local_dir)
# Attempt mounting of server share
retcode = subprocess.call(["/sbin/mount", "-t", "smbfs", remote_dir, local_dir])
if retcode != 0:
raise OSError("Mount operation failed")
请您参考如下方法:
这里有几个竞争条件。 Pythonic(和系统管理员)原则是请求宽恕比许可更容易。在这种情况下,这意味着最好尝试执行某个操作并检查其结果,而不是尝试猜测该操作是否会成功。
import errno
import os
import subprocess
def assert_remote_dir_is_mounted(remote_dir, local_dir):
# Make sure the directory exists.
try:
# Try it first. This avoids race conditions where two processes check
# for its existence at the same time.
os.makedirs(local_dir)
except OSError as exc:
# The "already exists" error is OK. Only report other error conditions.
if exc.errno != errno.EEXIST:
raise
retcode = subprocess.call(["/sbin/mount", "-t", "smbfs", remote_dir, local_dir])
# The call succeeded
if not retcode:
return True
# If it didn't succeed, see if the directory is on a different device
# from its parent. If it is, then the directory was already mounted,
# and hopefully on `remote_dir`. If that's sufficient, then you're done
# here. If you really need to verify that it's mounted on `remote_dir`,
# shell out to `mount` or otherwise check it.
local_parent = os.path.abspath(os.path.join(local_dir, os.pardir))
if os.stat(local_parent).st_dev != os.stat(local_dir).st_dev:
return True
return False
# or raise SomeException("couldn't mount"), etc.
