• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python iutil.open函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例5: 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


示例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


示例16: _getpwnam

    def _getpwnam(self, user_name, root):
        """Like pwd.getpwnam, but is able to use a different root.

           Also just returns the pwd structure as a list, because of laziness.
        """
        with open(root + "/etc/passwd", "r") as f:
            for line in f:
                fields = line.split(":")
                if fields[0] == user_name:
                    return fields

        return None
开发者ID:rtruxal,项目名称:anaconda,代码行数:12,代码来源:users.py


示例17: _getgrnam

    def _getgrnam(self, group_name, root):
        """Like grp.getgrnam, but able to use a different root.

            Just returns the grp structure as a list, same reason as above.
        """
        with open(root + "/etc/group", "r") as f:
            for line in f:
                fields = line.split(":")
                if fields[0] == group_name:
                    return fields

        return None
开发者ID:rtruxal,项目名称:anaconda,代码行数:12,代码来源:users.py


示例18: writeXdriver

 def writeXdriver(self, root=None):
     # this should go away at some point, but until it does, we
     # need to keep it around.
     if self.xdriver is None:
         return
     if root is None:
         root = iutil.getSysroot()
     if not os.path.isdir("%s/etc/X11" %(root,)):
         os.makedirs("%s/etc/X11" %(root,), mode=0o755)
     f = open("%s/etc/X11/xorg.conf" %(root,), 'w')
     f.write('Section "Device"\n\tIdentifier "Videocard0"\n\tDriver "%s"\nEndSection\n' % self.xdriver)
     f.close()
开发者ID:galleguindio,项目名称:anaconda,代码行数:12,代码来源:anaconda.py


示例19: _writeModuleBlacklist

    def _writeModuleBlacklist(self):
        """ Copy modules from modprobe.blacklist=<module> on cmdline to
            /etc/modprobe.d/anaconda-blacklist.conf so that modules will
            continue to be blacklisted when the system boots.
        """
        if "modprobe.blacklist" not in flags.cmdline:
            return

        iutil.mkdirChain(iutil.getSysroot() + "/etc/modprobe.d")
        with open(iutil.getSysroot() + "/etc/modprobe.d/anaconda-blacklist.conf", "w") as f:
            f.write("# Module blacklists written by anaconda\n")
            for module in flags.cmdline["modprobe.blacklist"].split():
                f.write("blacklist %s\n" % module)
开发者ID:NealSCarffery,项目名称:anaconda,代码行数:13,代码来源:__init__.py


示例20: 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:
            write_tmpfile(filename, str(self))
        else:
            # write directly to the file
            with open(filename, "w") as fobj:
                fobj.write(str(self))
开发者ID:nandakishore1006,项目名称:anaconda,代码行数:13,代码来源:simpleconfig.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python iutil.startProgram函数代码示例发布时间:2022-05-25
下一篇:
Python iutil.mkdirChain函数代码示例发布时间:2022-05-25
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap