只装载OS X卷如果它不只是挂载怎么办?

2024-06-24 13:40:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Python脚本装载osx卷。当卷已装入时(因此脚本无法装载到本地目录),如何防止出现错误?在

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")

Tags: path目录脚本ifremoteoslocaldef
2条回答

你有几个比赛条件。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.

您可以在/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"

相关问题 更多 >