仅在安装OS X X卷时才安装 - 如何?

时间:2014-03-03 17:11:44

标签: python

我正在使用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")

2 个答案:

答案 0 :(得分:1)

您可以在/ Volumes中查看已安装路径,如下所示:

mountedpath = os.path.join("/Volumes", local_dir)
if not os.path.exists(mountedpath):
    retcode = subprocess.call(["/sbin/mount", "-t", "smbfs", remote_dir, local_dir])
    if retcode != 0:
        raise OSError("Mount operation failed")
else:
    print "Mounted path found"

答案 1 :(得分:1)

这里有几个种族条件。 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.