当前位置: 首页>>代码示例>>Python>>正文


Python iutil.open函数代码示例

本文整理汇总了Python中pyanaconda.iutil.open函数的典型用法代码示例。如果您正苦于以下问题:Python open函数的具体用法?Python open怎么用?Python open使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了open函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: makeResolvConf

def makeResolvConf(instPath):
    """Make the resolv.conf file in the chroot."""
    if flags.imageInstall:
        return

    if not os.access("/etc/resolv.conf", os.R_OK):
        return

    if os.access("%s/etc/resolv.conf" %(instPath,), os.R_OK):
        f = open("%s/etc/resolv.conf" %(instPath,), "r")
        buf = f.read()
        f.close()
    else:
        buf = ""

    # already have a nameserver line, don't worry about it
    if buf.find("nameserver") != -1:
        return

    f = open("/etc/resolv.conf", "r")
    buf = f.read()
    f.close()

    # no nameserver, we can't do much about it
    if buf.find("nameserver") == -1:
        return

    shutil.copyfile("%s/etc/resolv.conf" %(instPath,),
                    "%s/etc/resolv.conf.bak" %(instPath,))
    f = open("%s/etc/resolv.conf" %(instPath,), "w+")
    f.write(buf)
    f.close()
开发者ID:rtruxal,项目名称:anaconda,代码行数:32,代码来源:rescue.py

示例2: write_timezone_config

def write_timezone_config(timezone, root):
    """
    Write timezone configuration for the system specified by root.

    :param timezone: ksdata.timezone object
    :param root: path to the root
    :raise: TimezoneConfigError

    """

    # we want to create a relative symlink
    tz_file = "/usr/share/zoneinfo/" + timezone.timezone
    rooted_tz_file = os.path.normpath(root + tz_file)
    relative_path = os.path.normpath("../" + tz_file)
    link_path = os.path.normpath(root + "/etc/localtime")

    if not os.access(rooted_tz_file, os.R_OK):
        log.error("Timezone to be linked (%s) doesn't exist", rooted_tz_file)
    else:
        try:
            # os.symlink fails if link_path exists, so try to remove it first
            os.remove(link_path)
        except OSError:
            pass

        try:
            os.symlink(relative_path, link_path)
        except OSError as oserr:
            log.error("Error when symlinking timezone (from %s): %s",
                      rooted_tz_file, oserr.strerror)

    if arch.isS390():
        # there is no HW clock on s390(x)
        return

    try:
        fobj = open(os.path.normpath(root + "/etc/adjtime"), "r")
        lines = fobj.readlines()
        fobj.close()
    except IOError:
        lines = ["0.0 0 0.0\n", "0\n"]

    try:
        with open(os.path.normpath(root + "/etc/adjtime"), "w") as fobj:
            fobj.write(lines[0])
            fobj.write(lines[1])
            if timezone.isUtc:
                fobj.write("UTC\n")
            else:
                fobj.write("LOCAL\n")
    except IOError as ioerr:
        msg = "Error while writing /etc/adjtime file: %s" % ioerr.strerror
        raise TimezoneConfigError(msg)
开发者ID:nandakishore1006,项目名称:anaconda,代码行数:53,代码来源:timezone.py

示例3: makeFStab

def makeFStab(instPath=""):
    if os.access("/proc/mounts", os.R_OK):
        f = open("/proc/mounts", "r")
        buf = f.read()
        f.close()
    else:
        buf = ""

    try:
        f = open(instPath + "/etc/fstab", "a")
        if buf:
            f.write(buf)
        f.close()
    except IOError as e:
        log.info("failed to write /etc/fstab: %s", e)
开发者ID:KosiehBarter,项目名称:anaconda,代码行数:15,代码来源:rescue.py

示例4: simple_replace

def simple_replace(fname, keys, add=True, add_comment="# Added by Anaconda"):
    """ Replace lines in a file, optionally adding if missing.

    :param str fname: Filename to operate on
    :param list keys: List of (key, string) tuples to search and replace
    :param bool add: When True add strings that were not replaced

    This will read all the lines in a file, looking for ones that start
    with keys and replacing the line with the associated string. The string
    should be a COMPLETE replacement for the line, not just a value.

    When add is True any keys that haven't been found will be appended
    to the end of the file along with the add_comment.
    """
    # Helper to return the line or the first matching key's string
    def _replace(l):
        r = [s for k,s in keys if l.startswith(k)]
        if r:
            return r[0]
        else:
            return l

    # Replace lines that match any of the keys
    with open(fname, "r") as f:
        lines = [_replace(l.strip()) for l in f]

    # Add any strings that weren't already in the file
    if add:
        append = [s for k,s in keys if not any(l.startswith(k) for l in lines)]
        if append:
            lines += [add_comment]
            lines += append

    write_tmpfile(fname, "\n".join(lines)+"\n")
开发者ID:nandakishore1006,项目名称:anaconda,代码行数:34,代码来源:simpleconfig.py

示例5: write

    def write(self, filename=None, use_tmp=True):
        """ passing filename will override the filename passed to init.
        """
        filename = filename or self.filename
        if not filename:
            return None

        if use_tmp:
            tmpf = tempfile.NamedTemporaryFile(mode="w", delete=False)
            tmpf.write(str(self))
            tmpf.close()

            # Move the temporary file (with 0600 permissions) over the top of the
            # original and preserve the original's permissions
            filename = os.path.realpath(filename)
            if os.path.exists(filename):
                m = os.stat(filename).st_mode
            else:
                m = int('0100644', 8)
            shutil.move(tmpf.name, filename)
            eintr_retry_call(os.chmod, filename, m)
        else:
            # write directly to the file
            with open(filename, "w") as fobj:
                fobj.write(str(self))
开发者ID:KosiehBarter,项目名称:anaconda,代码行数:25,代码来源:simpleconfig.py

示例6: get_servers_from_config

def get_servers_from_config(conf_file_path=NTP_CONFIG_FILE,
                            srv_regexp=SRV_LINE_REGEXP):
    """
    Goes through the chronyd's configuration file looking for lines starting
    with 'server'.

    :return: servers found in the chronyd's configuration
    :rtype: list

    """

    pools = list()
    servers = list()

    try:
        with open(conf_file_path, "r") as conf_file:
            for line in conf_file:
                match = srv_regexp.match(line)
                if match:
                    if match.group(1) == "pool":
                        pools.append(match.group(2))
                    else:
                        servers.append(match.group(2))

    except IOError as ioerr:
        msg = "Cannot open config file %s for reading (%s)" % (conf_file_path,
                                                               ioerr.strerror)
        raise NTPconfigError(msg)

    return (pools, servers)
开发者ID:nandakishore1006,项目名称:anaconda,代码行数:30,代码来源:ntp.py

示例7: isLpaeAvailable

def isLpaeAvailable():
    with open("/proc/cpuinfo", "r") as fobj:
        for line in fobj:
            if line.startswith("Features") and "lpae" in line.split():
                return True

    return False
开发者ID:nandakishore1006,项目名称:anaconda,代码行数:7,代码来源:__init__.py

示例8: dumpState

    def dumpState(self):
        from meh import ExceptionInfo
        from meh.dump import ReverseExceptionDump
        from inspect import stack as _stack
        from traceback import format_stack

        # Skip the frames for dumpState and the signal handler.
        stack = _stack()[2:]
        stack.reverse()
        exn = ReverseExceptionDump(ExceptionInfo(None, None, stack),
                                   self.mehConfig)

        # gather up info on the running threads
        threads = "\nThreads\n-------\n"
        for thread_id, frame in sys._current_frames().items():
            threads += "\nThread %s\n" % (thread_id,)
            threads += "".join(format_stack(frame))

        # dump to a unique file
        (fd, filename) = mkstemp(prefix="anaconda-tb-", dir="/tmp")
        dump_text = exn.traceback_and_object_dump(self)
        dump_text += threads
        dump_text_bytes = dump_text.encode("utf-8")
        iutil.eintr_retry_call(os.write, fd, dump_text_bytes)
        iutil.eintr_ignore(os.close, fd)

        # append to a given file
        with open("/tmp/anaconda-tb-all.log", "a+") as f:
            f.write("--- traceback: %s ---\n" % filename)
            f.write(dump_text + "\n")
开发者ID:galleguindio,项目名称:anaconda,代码行数:30,代码来源:anaconda.py

示例9: total_memory

def total_memory():
    """Returns total system memory in kB (given to us by /proc/meminfo)"""

    with open("/proc/meminfo", "r") as fobj:
        for line in fobj:
            if not line.startswith("MemTotal"):
                # we are only interested in the MemTotal: line
                continue

            fields = line.split()
            if len(fields) != 3:
                log.error("unknown format for MemTotal line in /proc/meminfo: %s", line.rstrip())
                raise RuntimeError("unknown format for MemTotal line in /proc/meminfo: %s" % line.rstrip())

            try:
                memsize = int(fields[1])
            except ValueError:
                log.error("ivalid value of MemTotal /proc/meminfo: %s", fields[1])
                raise RuntimeError("ivalid value of MemTotal /proc/meminfo: %s" % fields[1])

            # Because /proc/meminfo only gives us the MemTotal (total physical
            # RAM minus the kernel binary code), we need to round this
            # up. Assuming every machine has the total RAM MB number divisible
            # by 128.
            memsize /= 1024
            memsize = (memsize / 128 + 1) * 128
            memsize *= 1024

            log.info("%d kB (%d MB) are available", memsize, memsize / 1024)
            return memsize

        log.error("MemTotal: line not found in /proc/meminfo")
        raise RuntimeError("MemTotal: line not found in /proc/meminfo")
开发者ID:nandakishore1006,项目名称:anaconda,代码行数:33,代码来源:__init__.py

示例10: setUserSshKey

    def setUserSshKey(self, username, key, **kwargs):
        childpid = self._prepareChroot(kwargs.get("root", iutil.getSysroot()))

        if childpid == 0:
            user = self.admin.lookupUserByName(username)
            if not user:
                log.error("setUserSshKey: user %s does not exist", username)
                os._exit(1)

            homedir = user.get(libuser.HOMEDIRECTORY)[0]
            if not os.path.exists(homedir):
                log.error("setUserSshKey: home directory for %s does not exist", username)
                os._exit(1)

            sshdir = os.path.join(homedir, ".ssh")
            if not os.path.isdir(sshdir):
                os.mkdir(sshdir, 0o700)
                iutil.eintr_retry_call(os.chown, sshdir, user.get(libuser.UIDNUMBER)[0], user.get(libuser.GIDNUMBER)[0])

            authfile = os.path.join(sshdir, "authorized_keys")
            authfile_existed = os.path.exists(authfile)
            with open(authfile, "a") as f:
                f.write(key + "\n")

            # Only change mode and ownership if we created it
            if not authfile_existed:
                iutil.eintr_retry_call(os.chmod, authfile, 0o600)
                iutil.eintr_retry_call(os.chown, authfile, user.get(libuser.UIDNUMBER)[0], user.get(libuser.GIDNUMBER)[0])
                iutil.execWithRedirect("restorecon", ["-r", sshdir])
            os._exit(0)
        else:
            return self._finishChroot(childpid)
开发者ID:KosiehBarter,项目名称:anaconda,代码行数:32,代码来源:users.py

示例11: load_firmware_language

def load_firmware_language(lang, text_mode=False):
    """
    Procedure that loads firmware language information (if any). It stores the
    information in the given ksdata.lang object and sets the $LANG environment
    variable.

    This method must be run before any other threads are started.

    :param lang: ksdata.lang object
    :return: None
    :rtype: None

    """

    if lang.lang and lang.seen:
        # set in kickstart, do not override
        return

    try:
        n = "/sys/firmware/efi/efivars/PlatformLang-8be4df61-93ca-11d2-aa0d-00e098032b8c"
        d = open(n, 'r', 0).read()
    except IOError:
        return

    # the contents of the file are:
    # 4-bytes of attribute data that we don't care about
    # NUL terminated ASCII string like 'en-US'.
    if len(d) < 10:
        log.debug("PlatformLang was too short")
        return
    d = d[4:]
    if d[2] != '-':
        log.debug("PlatformLang was malformed")
        return

    # they use - and we use _, so fix it...
    d = d[:2] + '_' + d[3:-1]

    # UEFI 2.3.1 Errata C specifies 2 aliases in common use that
    # aren't part of RFC 4646, but are allowed in PlatformLang.
    # Because why make anything simple?
    if d.startswith('zh_chs'):
        d = 'zh_Hans'
    elif d.startswith('zh_cht'):
        d = 'zh_Hant'
    d += '.UTF-8'

    if not is_supported_locale(d):
        log.debug("PlatformLang was '%s', which is unsupported.", d)
        return

    locales = get_language_locales(d)
    if not locales:
        log.debug("No locales found for the PlatformLang '%s'.", d)
        return

    log.debug("Using UEFI PlatformLang '%s' ('%s') as our language.", d, locales[0])
    setup_locale(locales[0], lang, text_mode)

    os.environ["LANG"] = locales[0] # pylint: disable=environment-modify
开发者ID:NealSCarffery,项目名称:anaconda,代码行数:60,代码来源:localization.py

示例12: _groupExists

    def _groupExists(self, group_name, root):
        """Returns whether a group with the given name already exists."""
        with open(root + "/etc/group", "r") as f:
            for line in f:
                if line.split(":")[0] == group_name:
                    return True

        return False
开发者ID:marmarek,项目名称:qubes-installer-qubes-os,代码行数:8,代码来源:users.py

示例13: getMediaId

def getMediaId(path):
    if os.access("%s/.discinfo" % path, os.R_OK):
        f = open("%s/.discinfo" % path)
        newStamp = f.readline().strip()
        f.close()

        return newStamp
    else:
        return None
开发者ID:KosiehBarter,项目名称:anaconda,代码行数:9,代码来源:image.py

示例14: _ensureLoginDefs

    def _ensureLoginDefs(self, root):
        """Runs a command after creating /etc/login.defs, if necessary.

           groupadd and useradd need login.defs to exist in the chroot, and if
           someone is doing a cloud image install or some kind of --nocore thing
           it may not. An empty one is ok, though. If it's missing, create it,
           run the command, then clean it up.
        """
        login_defs_path = root + "/etc/login.defs"
        if not os.path.exists(login_defs_path):
            open(login_defs_path, "w").close()
            login_defs_created = True
        else:
            login_defs_created = False

        yield

        if login_defs_created:
            os.unlink(login_defs_path)
开发者ID:rtruxal,项目名称:anaconda,代码行数:19,代码来源:users.py

示例15: isIsoImage

def isIsoImage(path):
    try:
        with open(path, "rb") as isoFile:
            for blockNum in range(16, 100):
                isoFile.seek(blockNum * ISO_BLOCK_SIZE + 1)
                if isoFile.read(5) == b"CD001":
                    return True
    except IOError:
        pass

    return False
开发者ID:nandakishore1006,项目名称:anaconda,代码行数:11,代码来源:__init__.py


注:本文中的pyanaconda.iutil.open函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。