python linecache source code

The source code of linecache.py from python 2.0 is here.

from stat import *

Get file information

>>> filestat = os.stat(‘README.TXT‘)
>>> filestat
nt.stat_result(st_mode=33206, st_ino=0L, st_dev=0, st_nlink=0, st_uid=0, st_gid=0, st_size=2623L, st_atime=1450607830L, st_mtime=1398844440L, st_ctime=1398844440L)
>>> filestat.st_mtime
1398844440.0
>>> import stat
>>> from stat import *
>>> filestat[ST_MTIME]
1398844440L

Notice filesta.st_mtime is a float number while filestat[ST_MTIME] is a long number which is strange.

Each cache is a entry is a dictionary with key=filename value=(size, mtime, lines, fullnames) (line 91)

Cache is only updated when a cache miss occurs. (line 39)

Function checkcache() is NOT called automatically and it seems that the user should call this function manually.

Source Code

 1 """Cache lines from files.
 2
 3 This is intended to read lines from modules imported -- hence if a filename
 4 is not found, it will look down the module search path for a file by
 5 that name.
 6 """
 7
 8 import sys
 9 import os
10 from stat import *
11
12 def getline(filename, lineno):
13     lines = getlines(filename)
14     if 1 <= lineno <= len(lines):
15         return lines[lineno-1]
16     else:
17         return ‘‘
18
19
20 # The cache
21
22 cache = {} # The cache
23
24
25 def clearcache():
26     """Clear the cache entirely."""
27
28     global cache
29     cache = {}
30
31
32 def getlines(filename):
33     """Get the lines for a file from the cache.
34     Update the cache if it doesn‘t contain an entry for this file already."""
35
36     if cache.has_key(filename):
37         return cache[filename][2]
38     else:
39         return updatecache(filename)
40
41
42 def checkcache():
43     """Discard cache entries that are out of date.
44     (This is not checked upon each call!)"""
45
46     for filename in cache.keys():
47         size, mtime, lines, fullname = cache[filename]
48         try:
49             stat = os.stat(fullname)
50         except os.error:
51             del cache[filename]
52             continue
53         if size <> stat[ST_SIZE] or mtime <> stat[ST_MTIME]:
54             del cache[filename]
55
56
57 def updatecache(filename):
58     """Update a cache entry and return its list of lines.
59     If something‘s wrong, print a message, discard the cache entry,
60     and return an empty list."""
61
62     if cache.has_key(filename):
63         del cache[filename]
64     if not filename or filename[0] + filename[-1] == ‘<>‘:
65         return []
66     fullname = filename
67     try:
68         stat = os.stat(fullname)
69     except os.error, msg:
70         # Try looking through the module search path
71         basename = os.path.split(filename)[1]
72         for dirname in sys.path:
73             fullname = os.path.join(dirname, basename)
74             try:
75                 stat = os.stat(fullname)
76                 break
77             except os.error:
78                 pass
79         else:
80             # No luck
81 ##          print ‘*** Cannot stat‘, filename, ‘:‘, msg
82             return []
83     try:
84         fp = open(fullname, ‘r‘)
85         lines = fp.readlines()
86         fp.close()
87     except IOError, msg:
88 ##      print ‘*** Cannot open‘, fullname, ‘:‘, msg
89         return []
90     size, mtime = stat[ST_SIZE], stat[ST_MTIME]
91     cache[filename] = size, mtime, lines, fullname
92     return lines
时间: 2024-10-20 01:17:30

python linecache source code的相关文章

convert source code to pdf in python

1 import os 2 import sys 3 4 def find_file(root_dir, type): 5 dirs_pool = [root_dir] 6 dest_pool = [] 7 8 def scan_dir(directory): 9 entries = os.walk(directory) 10 for root, dirs, files in entries: 11 dirs_pool.extend([os.path.join(root, dir_entry)

Defining Python Source Code Encodings

Defining the Encoding Python will default to ASCII as standard encoding if no other encoding hints are given. To define a source code encoding, a magic comment must be placed into the source files either as first or second line in the file, such as:

Source Code Structure - Python 源码结构

Source Code Structure - Python 源码结构 Include 目录包含了 Python 提供的所有头文件, 如果用户需要用 C 或 C++ 编写自定义模块扩展 Python, 那么就需要用到这里提供的头文件. Lib 目录包含了 Python 自带的所有标准库, 其中的库都是用 Python 写的. Moudles 目录包含了所有用 C 语言写的模块, 是那些对速度要求非常严格的模块, 如 random, cStringIO 等. 然而一些对速度要求不高的模块,如 os

12 Source Code Profilers for C &amp; C++

Source :http://open-tube.com/12-source-code-profilers-for-cc/ Code Profilers are very distinct from traditional debuggers. They are able to catch the trivial and non fatal coding errors which are often hard for humans to catch. These trivial bugs lat

CRC32 Source Code

/* The Quest Operating System * Copyright (C) 2005-2010 Richard West, Boston University * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Softwar

【开源】海看源代码统计工具 Haikan Source Code Counter

Haikan Source Code Counter 海看源代码统计工具 BY 杭州海看网络科技有限公司 ------------------- github上的地址: https://github.com/haikanwhf/HaikanSourceCodeCounter ------------------ 海看源代码统计工具V1.7.rar

Tips for newbie to read source code

作者:ll kid链接:https://zhuanlan.zhihu.com/p/23796485来源:知乎著作权归作者所有.商业转载请联系作者获得授权,非商业转载请注明出处. This post is first posted on my WeChat public account: GeekArtT Reading source code is always one big part for software engineers. Just like the writers to learn

About building ant & install ant on centos7 {ant source code 1.94}

? ? ? ? ? ? ? hamcrest-junit-2.0.0.0.jar java-hamcrest-2.0.0.0.jar ? copy to ant-sourceCodeDir/lib/optimal ? ? ? ? About building ant & install ant on centos7 {ant source code 1.94}

退役笔记一#MySQL = lambda sql : sql + &#39; Source Code 4 Explain Plan &#39;

Mysql 查询执行过程 大致分为4个阶段吧: 语法分析(sql_parse.cc<词法分析, 语法分析, 语义检查 >) >>sql_resolver.cc # JOIN.prepare 生成逻辑查询plan(sql_optimizer.cc) >># JOIN.optimize 生成物理查询plan(sql_planner.cc) run the explain plan(sql_executor.cc) 退役笔记一#MySQL = lambda sql : sql