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


Python os.stat_result方法代码示例

本文整理汇总了Python中os.stat_result方法的典型用法代码示例。如果您正苦于以下问题:Python os.stat_result方法的具体用法?Python os.stat_result怎么用?Python os.stat_result使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在os的用法示例。


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

示例1: test_update_timestamp

# 需要导入模块: import os [as 别名]
# 或者: from os import stat_result [as 别名]
def test_update_timestamp():
    with tempfile.TemporaryDirectory() as tmpdirname:
        path = Path(tmpdirname, 'tmp_update_timestamp')
        path.touch()
        orig_stats: os.stat_result = path.stat()

        # Add delta to timestamp
        with domain_substitution._update_timestamp(path, set_new=True):
            with path.open('w') as fileobj:
                fileobj.write('foo')

        new_stats: os.stat_result = path.stat()
        assert orig_stats.st_atime_ns != new_stats.st_atime_ns
        assert orig_stats.st_mtime_ns != new_stats.st_mtime_ns

        # Remove delta from timestamp
        with domain_substitution._update_timestamp(path, set_new=False):
            with path.open('w') as fileobj:
                fileobj.write('bar')

        new_stats: os.stat_result = path.stat()
        assert orig_stats.st_atime_ns == new_stats.st_atime_ns
        assert orig_stats.st_mtime_ns == new_stats.st_mtime_ns 
开发者ID:Eloston,项目名称:ungoogled-chromium,代码行数:25,代码来源:test_domain_substitution.py

示例2: test_oldSingleDigitDayOfMonth

# 需要导入模块: import os [as 别名]
# 或者: from os import stat_result [as 别名]
def test_oldSingleDigitDayOfMonth(self):
        """
        A file with a high-resolution timestamp which falls on a day of the
        month which can be represented by one decimal digit is formatted with
        one padding 0 to preserve the columns which come after it.
        """
        # A point about 7 months in the past, tweaked to fall on the first of a
        # month so we test the case we want to test.
        then = self.now - (60 * 60 * 24 * 31 * 7) + (60 * 60 * 24 * 5)
        stat = os.stat_result((0, 0, 0, 0, 0, 0, 0, 0, then, 0))

        self.assertEqual(
            self._lsInTimezone('America/New_York', stat),
            '!---------    0 0        0               0 May 01  1973 foo')
        self.assertEqual(
            self._lsInTimezone('Pacific/Auckland', stat),
            '!---------    0 0        0               0 May 02  1973 foo') 
开发者ID:proxysh,项目名称:Safejumper-for-Desktop,代码行数:19,代码来源:test_cftp.py

示例3: test_localeIndependent

# 需要导入模块: import os [as 别名]
# 或者: from os import stat_result [as 别名]
def test_localeIndependent(self):
        """
        The month name in the date is locale independent.
        """
        # A point about three months in the past.
        then = self.now - (60 * 60 * 24 * 31 * 3)
        stat = os.stat_result((0, 0, 0, 0, 0, 0, 0, 0, then, 0))

        # Fake that we're in a language where August is not Aug (e.g.: Spanish)
        currentLocale = locale.getlocale()
        locale.setlocale(locale.LC_ALL, "es_AR.UTF8")
        self.addCleanup(locale.setlocale, locale.LC_ALL, currentLocale)

        self.assertEqual(
            self._lsInTimezone('America/New_York', stat),
            '!---------    0 0        0               0 Aug 28 17:33 foo')
        self.assertEqual(
            self._lsInTimezone('Pacific/Auckland', stat),
            '!---------    0 0        0               0 Aug 29 09:33 foo')

    # If alternate locale is not available, the previous test will be
    # skipped, please install this locale for it to run 
开发者ID:proxysh,项目名称:Safejumper-for-Desktop,代码行数:24,代码来源:test_cftp.py

示例4: test_newSingleDigitDayOfMonth

# 需要导入模块: import os [as 别名]
# 或者: from os import stat_result [as 别名]
def test_newSingleDigitDayOfMonth(self):
        """
        A file with a high-resolution timestamp which falls on a day of the
        month which can be represented by one decimal digit is formatted with
        one padding 0 to preserve the columns which come after it.
        """
        # A point about three months in the past, tweaked to fall on the first
        # of a month so we test the case we want to test.
        then = self.now - (60 * 60 * 24 * 31 * 3) + (60 * 60 * 24 * 4)
        stat = os.stat_result((0, 0, 0, 0, 0, 0, 0, 0, then, 0))

        self.assertEqual(
            self._lsInTimezone('America/New_York', stat),
            '!---------    0 0        0               0 Sep 01 17:33 foo')
        self.assertEqual(
            self._lsInTimezone('Pacific/Auckland', stat),
            '!---------    0 0        0               0 Sep 02 09:33 foo') 
开发者ID:proxysh,项目名称:Safejumper-for-Desktop,代码行数:19,代码来源:test_cftp.py

示例5: mock_stat

# 需要导入模块: import os [as 别名]
# 或者: from os import stat_result [as 别名]
def mock_stat(mocker):
    def function():
        a_stat = list(os.stat(__file__))
        stat_results = []
        for x in range(5):
            a_stat[-2] += 1
            stat_results.append(os.stat_result(a_stat))
        mocker.patch('os.stat', side_effect=stat_results)
    return function


# TODO
# def test_watcher(waiter, mock_stat):
#     mock_stat()
#     def 
#     file_watcher = FileWatcher()
#     event = file_watcher.get_event()
#     assert event.is_set()
#     task = asyncio.create_task(waiter()(event))
#     await task
#     assert not event.is_set() 
开发者ID:bartok765,项目名称:galaxy_blizzard_plugin,代码行数:23,代码来源:test_watcher.py

示例6: _write_pyc

# 需要导入模块: import os [as 别名]
# 或者: from os import stat_result [as 别名]
def _write_pyc(
        state: "AssertionState",
        co: types.CodeType,
        source_stat: os.stat_result,
        pyc: Path,
    ) -> bool:
        try:
            with atomic_write(fspath(pyc), mode="wb", overwrite=True) as fp:
                _write_pyc_fp(fp, source_stat, co)
        except OSError as e:
            state.trace("error writing pyc file at {}: {}".format(pyc, e))
            # we ignore any failure to write the cache file
            # there are many reasons, permission-denied, pycache dir being a
            # file etc.
            return False
        return True 
开发者ID:pytest-dev,项目名称:pytest,代码行数:18,代码来源:rewrite.py

示例7: rpmExpandMacro

# 需要导入模块: import os [as 别名]
# 或者: from os import stat_result [as 别名]
def rpmExpandMacro(val):
    if getattr(rpm, '_rpm', ''):
        rawRpmModulePath = rpm._rpm.__file__
    else:
        rawRpmModulePath = rpm.__file__
    sonames = [ x[1] for x in elf.inspect(rawRpmModulePath)[0]
                    if x[0] == 'soname']
    rpmLibs = [ x for x in sonames if re.match('librpm[-\.].*so', x) ]
    assert(len(rpmLibs) == 1)
    librpm = ctypes.CDLL(rpmLibs[0])
    librpm.expandMacros.argtypes = (c_void_p, c_void_p, c_void_p, c_long)
    librpm.expandMacros.restype = c_int

    buf = ctypes.create_string_buffer(val, len(val) * 100)
    rc = librpm.expandMacros(None, None, buf, len(buf))
    if rc != 0:
        raise RuntimeError("failed to expand RPM macro %r" % (val,))
    return buf.value


# os.stat_result doesn't seem to be usable if you need to populate the fields
# after st_ctime, e.g. rdev 
开发者ID:sassoftware,项目名称:conary,代码行数:24,代码来源:rpmcapsule.py

示例8: _make_details_from_stat

# 需要导入模块: import os [as 别名]
# 或者: from os import stat_result [as 别名]
def _make_details_from_stat(cls, stat_result):
        # type: (os.stat_result) -> Dict[Text, object]
        """Make a *details* info dict from an `os.stat_result` object.
        """
        details = {
            "_write": ["accessed", "modified"],
            "accessed": stat_result.st_atime,
            "modified": stat_result.st_mtime,
            "size": stat_result.st_size,
            "type": int(cls._get_type_from_stat(stat_result)),
        }
        # On other Unix systems (such as FreeBSD), the following
        # attributes may be available (but may be only filled out if
        # root tries to use them):
        details["created"] = getattr(stat_result, "st_birthtime", None)
        ctime_key = "created" if _WINDOWS_PLATFORM else "metadata_changed"
        details[ctime_key] = stat_result.st_ctime
        return details 
开发者ID:PyFilesystem,项目名称:pyfilesystem2,代码行数:20,代码来源:osfs.py

示例9: _make_access_from_stat

# 需要导入模块: import os [as 别名]
# 或者: from os import stat_result [as 别名]
def _make_access_from_stat(cls, stat_result):
        # type: (os.stat_result) -> Dict[Text, object]
        """Make an *access* info dict from an `os.stat_result` object.
        """
        access = {}  # type: Dict[Text, object]
        access["permissions"] = Permissions(mode=stat_result.st_mode).dump()
        access["gid"] = gid = stat_result.st_gid
        access["uid"] = uid = stat_result.st_uid
        if not _WINDOWS_PLATFORM:
            import grp
            import pwd

            try:
                access["group"] = grp.getgrgid(gid).gr_name
            except KeyError:  # pragma: no cover
                pass

            try:
                access["user"] = pwd.getpwuid(uid).pw_name
            except KeyError:  # pragma: no cover
                pass
        return access 
开发者ID:PyFilesystem,项目名称:pyfilesystem2,代码行数:24,代码来源:osfs.py

示例10: test_oldFile

# 需要导入模块: import os [as 别名]
# 或者: from os import stat_result [as 别名]
def test_oldFile(self):
        """
        A file with an mtime six months (approximately) or more in the past has
        a listing including a low-resolution timestamp.
        """
        # Go with 7 months.  That's more than 6 months.
        then = self.now - (60 * 60 * 24 * 31 * 7)
        stat = os.stat_result((0, 0, 0, 0, 0, 0, 0, 0, then, 0))

        self.assertEqual(
            self._lsInTimezone('America/New_York', stat),
            '!---------    0 0        0               0 Apr 26  1973 foo')
        self.assertEqual(
            self._lsInTimezone('Pacific/Auckland', stat),
            '!---------    0 0        0               0 Apr 27  1973 foo') 
开发者ID:proxysh,项目名称:Safejumper-for-Desktop,代码行数:17,代码来源:test_cftp.py

示例11: test_newFile

# 需要导入模块: import os [as 别名]
# 或者: from os import stat_result [as 别名]
def test_newFile(self):
        """
        A file with an mtime fewer than six months (approximately) in the past
        has a listing including a high-resolution timestamp excluding the year.
        """
        # A point about three months in the past.
        then = self.now - (60 * 60 * 24 * 31 * 3)
        stat = os.stat_result((0, 0, 0, 0, 0, 0, 0, 0, then, 0))

        self.assertEqual(
            self._lsInTimezone('America/New_York', stat),
            '!---------    0 0        0               0 Aug 28 17:33 foo')
        self.assertEqual(
            self._lsInTimezone('Pacific/Auckland', stat),
            '!---------    0 0        0               0 Aug 29 09:33 foo') 
开发者ID:proxysh,项目名称:Safejumper-for-Desktop,代码行数:17,代码来源:test_cftp.py

示例12: get_disk_usage_one

# 需要导入模块: import os [as 别名]
# 或者: from os import stat_result [as 别名]
def get_disk_usage_one(st):
    '''Extract disk usage of one inode from its stat_result struct.

    If known, get real disk usage, as written to device by filesystem, not
    logical file size. Those values may be different for sparse files.

    :param os.stat_result st: stat result
    :returns: disk usage
    '''
    try:
        return st.st_blocks * BLKSIZE
    except AttributeError:
        return st.st_size 
开发者ID:QubesOS,项目名称:qubes-core-admin,代码行数:15,代码来源:file.py

示例13: testExtractEventsFromSourcesWithFilestat

# 需要导入模块: import os [as 别名]
# 或者: from os import stat_result [as 别名]
def testExtractEventsFromSourcesWithFilestat(self):
    """Tests the ExtractEventsFromSources function with filestat parser."""
    output_writer = test_lib.TestOutputWriter(encoding=self._OUTPUT_ENCODING)
    test_tool = log2timeline_tool.Log2TimelineTool(output_writer=output_writer)

    source_path = self._GetTestFilePath(['test_pe.exe'])
    options = self._CreateExtractionOptions(source_path)
    options.parsers = 'filestat,pe'

    with shared_test_lib.TempDirectory() as temp_directory:
      options.storage_file = os.path.join(temp_directory, 'storage.plaso')
      options.storage_format = definitions.STORAGE_FORMAT_SQLITE
      options.task_storage_format = definitions.STORAGE_FORMAT_SQLITE

      test_tool.ParseOptions(options)

      test_tool.ExtractEventsFromSources()

      storage_file = sqlite_file.SQLiteStorageFile()
      try:
        storage_file.Open(path=options.storage_file, read_only=True)
      except IOError as exception:
        self.fail((
            'Unable to open storage file after processing with error: '
            '{0!s}.').format(exception))

      # There should be 3 filestat and 3 pe parser generated events.
      # Typically there are 3 filestat events, but there can be 4 on platforms
      # that support os.stat_result st_birthtime.
      expected_event_counters = {
          'fs:stat': [3, 4],
          'pe:delay_import:import_time': 1,
          'pe:import:import_time': 1,
          'pe:compilation:compilation_time': 1}

      self.CheckEventCounters(storage_file, expected_event_counters) 
开发者ID:log2timeline,项目名称:plaso,代码行数:38,代码来源:log2timeline_tool.py

示例14: mock_reload_env

# 需要导入模块: import os [as 别名]
# 或者: from os import stat_result [as 别名]
def mock_reload_env():
    """Set up the mock environment for unit-testing the reloader module."""
    # For unmodified files, just return a fake stat result with everything set
    # to 0.
    unmodified_stat_result = os.stat_result(0 for _ in range(10))

    # For modified files, set the st_mtime to 1 day in the future. It doesn't
    # matter that the modification time is in the future - just so long as it
    # is greater than the current time. The reloader only checks st_mtime,
    # which is the value at the 8th index passed to os.stat_result.
    one_day_hence = time.time() + 24 * 60 * 60
    modified_stat_result = os.stat_result(
        0 if i != 8 else one_day_hence for i in range(10)
    )

    def mock_stat(filepath):
        if filepath in mock_stat.modified_files:
            return modified_stat_result
        else:
            return unmodified_stat_result

    mock_stat.modified_files = set()

    reloader_patch = "testplan.runnable.interactive.reloader.reload_module"
    with mock.patch("modulefinder.ModuleFinder", new=MockModuleFinder), (
        mock.patch(reloader_patch, side_effect=lambda module: module)
    ) as mock_reload, (mock.patch("os.stat", new=mock_stat)), (
        mock.patch("sys.modules", new=MOCK_SYSMODULES)
    ):

        # Despite mocking modulefinder.ModuleFinder above, we also need to
        # swap out the real ModuleFinder with our mock one in the list of
        # bases for the GraphModuleFinder.
        reloader._GraphModuleFinder.__bases__ = (
            MockModuleFinder,
            logger.Loggable,
        )
        reload_obj = reloader.ModuleReloader()

        yield reload_obj, mock_reload, mock_stat 
开发者ID:Morgan-Stanley,项目名称:testplan,代码行数:42,代码来源:test_reloader.py

示例15: _write_pyc_fp

# 需要导入模块: import os [as 别名]
# 或者: from os import stat_result [as 别名]
def _write_pyc_fp(
    fp: IO[bytes], source_stat: os.stat_result, co: types.CodeType
) -> None:
    # Technically, we don't have to have the same pyc format as
    # (C)Python, since these "pycs" should never be seen by builtin
    # import. However, there's little reason deviate.
    fp.write(importlib.util.MAGIC_NUMBER)
    # as of now, bytecode header expects 32-bit numbers for size and mtime (#4903)
    mtime = int(source_stat.st_mtime) & 0xFFFFFFFF
    size = source_stat.st_size & 0xFFFFFFFF
    # "<LL" stands for 2 unsigned longs, little-ending
    fp.write(struct.pack("<LL", mtime, size))
    fp.write(marshal.dumps(co)) 
开发者ID:pytest-dev,项目名称:pytest,代码行数:15,代码来源:rewrite.py


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