Python 模块 | 栗子姑娘

转载请注明出处:https://www.cnblogs.com/Chestnut-g/

  1. 模块的含义:

  用一砣代码实现了某个功能的代码集合。 类似于函数式编程和面向过程编程,函数式编程则完成一个功能,其他代码用来调用即可,提供了代码的重用性和代码间的耦合。而对于一个复杂的功能来,可能需要多个函数才能完成(函数又可以在不同的.py文件中),n个 .py 文件组成的代码集合就称为模块。

  2.模块的分类:

  模块可分为三种:

  • 自定义模块
  • 第三方模块
  • 内置模块
自定义模块
  • 定义模块

情景一:

Python   模块-LMLPHP

情景二:

Python   模块-LMLPHP

情景三:

Python   模块-LMLPHP

  • 导入模块:
'''
#import test1    #导入单个模块
#import test1,random   #导入多个模块
#test1.test()     #调用test的方法
#from test1 import *   #导入模块中的所有函数;*号表示占位符,表示所有方法(指定方法)
#from test1 import sayhi as SH   #使用as给函数指定别名
'''

import test1中test1就是自定义模块,你可以导入其他模块中使用。

内置模块

  如:os 是系统相关的模块;file是文件操作相关的模块

  • sys模块
'''
#import sys   #sys:系统路径
#from package时先访问init.py文件
#访问属性时直接打印,即不加括号
#访问方法时,需要调用,即加括号()
'''

#import sys   #sys:系统路径
import sys,os
print(sys.path)
a = os.path.abspath(__file__)
#__file__表示当前程序或文件
# os.path.abspath表示拿到本文件或本程序的路径
b = os.path.dirname(a)  #拿到当前文件的父目录
c = os.path.dirname(b)  #拿到a,b的共同目录
print(a)
print(b)
print(c)
sys.path.append(c)     #sys.path.append把找到的路径插入到sys.path路径当中

#首先访问的是init.py文件
from package import *

#访问属性v
from package.test import v
print(v)

#访问方法
from package import test1
test1.test1()
Python   模块-LMLPHPPython   模块-LMLPHP
  1 # import sys,os
  2 # print(sys.path)
  3 # a = os.path.abspath(__file__)
  4 # b = os.path.dirname(a)
  5 # c = os.path.dirname(b)
  6 # print(a)
  7 # print(b)
  8 # print(c)
  9 # # sys.path.append(c)     #sys.path.append把找到的路径插入到sys.path路径当中
 10 # import test1
 11 # test1.test1()
 12 #
 13 # v = "rythhjyetyu"
 14 # def t():
 15 #     print("fuhf")
 16
 17
 18 # encoding: utf-8
 19 # module sys
 20 # from (built-in)
 21 # by generator 1.145
 22 """
 23 This module provides access to some objects used or maintained by the
 24 interpreter and to functions that interact strongly with the interpreter.
 25 #这个模块提供了对一些对象的访问以及与解释器强烈交互的函数
 26
 27 Dynamic objects:
 28 #动态对象
 29
 30 argv -- command line arguments; argv[0] is the script pathname if known
 31 #argv——命令行参数;如果已知,argv[0]是脚本路径名
 32
 33 path -- module search path; path[0] is the script directory, else ''
 34 #路径——模块搜索路径;路径[0]是脚本目录,否则为空目录
 35
 36 modules -- dictionary of loaded modules
 37 模块——加载的模块字典
 38
 39 displayhook -- called to show results in an interactive session
 40 #displayhook——在交互式会话中显示结果的调用
 41
 42 excepthook -- called to handle any uncaught exception other than SystemExit
 43   To customize printing in an interactive session or to install a custom
 44   top-level exception handler, assign other functions to replace these.
 45 #excepthook——调用来处理除SystemExit之外的任何未捕获的异常在交互式会话中定制打印
 46 或安装定制顶级异常处理程序,分配其他函数来替换这些。
 47
 48 stdin -- standard input file object; used by input()
 49 #标准输入文件对象;通过input()输入
 50
 51 stdout -- standard output file object; used by print()
 52 #标准输出文件对象;通过print()输出
 53 stderr -- standard error object; used for error messages
 54   By assigning other file objects (or objects that behave like files)
 55   to these, it is possible to redirect all of the interpreter's I/O.
 56 #标准错误对象;用于错误消息通过分配其他文件对象(或行为类似于文件的对象)
 57 对于这些,可以重定向所有解释器的I/O
 58
 59 last_type -- type of last uncaught exception
 60 #最后一个未捕获异常的类型
 61
 62 last_value -- value of last uncaught exception
 63 #最后一个未捕获异常的值
 64
 65 last_traceback -- traceback of last uncaught exception
 66 #上次未捕获异常的回溯
 67
 68   These three are only available in an interactive session after a
 69   traceback has been printed.
 70   #这三个只在a之后的交互会话中可用回溯已经打印出来了。
 71
 72 Static objects:
 73 #静态对象:
 74
 75 builtin_module_names -- tuple of module names built into this interpreter
 76 #builtin_module_names——内置于此解释器中的模块名称的元组
 77
 78 copyright -- copyright notice pertaining to this interpreter
 79  80
 81 exec_prefix -- prefix used to find the machine-specific Python library
 82 #exec_prefix——用于查找特定于机器的Python库的前缀
 83
 84 executable -- absolute path of the executable binary of the Python interpreter
 85 #可执行——Python解释器可执行二进制文件的绝对路径
 86
 87 float_info -- a struct sequence with information about the float implementation.
 88 #float_info——一个包含关于浮点实现信息的结构序列。
 89
 90 float_repr_style -- string indicating the style of repr() output for floats
 91 #float_repr_style——字符串,指示浮点数的repr()输出的样式
 92
 93 hash_info -- a struct sequence with information about the hash algorithm.
 94 #hash_info——一个包含散列算法信息的结构序列。
 95
 96 hexversion -- version information encoded as a single integer
 97 #hexversion——将版本信息编码为单个整数
 98
 99 implementation -- Python implementation information.
100 #实现——Python实现信息。
101
102 int_info -- a struct sequence with information about the int implementation.
103 #int_info——一个包含int实现信息的结构序列。
104
105 maxsize -- the largest supported length of containers.
106 #最大支持的容器长度。
107
108 maxunicode -- the value of the largest Unicode code point
109 #maxunicode——最大的Unicode编码点的值
110
111 platform -- platform identifier  #平台——平台标识符
112
113 prefix -- prefix used to find the Python library
114 #前缀——用于查找Python库的前缀
115
116 thread_info -- a struct sequence with information about the thread implementation.
117 #thread_info——一个包含线程实现信息的结构序列。
118
119 version -- the version of this interpreter as a string
120 #版本——这个解释器作为字符串的版本
121
122 version_info -- version information as a named tuple
123 #version_info——版本信息作为一个命名元组
124
125 dllhandle -- [Windows only] integer handle of the Python DLL
126 #dllhandle——[Windows专用] Python DLL的整数句柄
127
128 winver -- [Windows only] version number of the Python DLL
129 #winver——[Windows专用]Python DLL的版本号
130
131 _enablelegacywindowsfsencoding -- [Windows only]
132 __stdin__ -- the original stdin; don't touch!
133 __stdout__ -- the original stdout; don't touch!
134 __stderr__ -- the original stderr; don't touch!
135 __displayhook__ -- the original displayhook; don't touch!
136 __excepthook__ -- the original excepthook; don't touch!
137
138 Functions:
139 #功能:
140
141 displayhook() -- print an object to the screen, and save it in builtins._
142 #displayhook()——将对象打印到屏幕上,并将其保存在build ._中
143
144 excepthook() -- print an exception and its traceback to sys.stderr
145 #excepthook()——打印一个异常及其回溯到sys.stderr的回溯
146
147 exc_info() -- return thread-safe information about the current exception
148 #exc_info()——返回关于当前异常的线程安全信息
149
150 exit() -- exit the interpreter by raising SystemExit
151 #exit()——通过提升SystemExit来退出解释器
152
153 getdlopenflags() -- returns flags to be used for dlopen() calls
154 #getdlopenflags()——返回用于dlopen()调用的标志
155
156 getprofile() -- get the global profiling function
157 #getprofile()——获取全局配置函数
158
159 getrefcount() -- return the reference count for an object (plus one :-)
160 #getrefcount()——返回对象的引用计数(加1:-)
161
162 getrecursionlimit() -- return the max recursion depth for the interpreter
163 #getrecursionlimit()——返回解释器的最大递归深度
164
165 getsizeof() -- return the size of an object in bytes
166 #getsizeof()——以字节为单位返回对象的大小
167
168 gettrace() -- get the global debug tracing function
169 #gettrace()——获取全局调试跟踪函数
170
171 setcheckinterval() -- control how often the interpreter checks for events
172 #setcheckinterval()——控制解释器检查事件的频率
173
174 setdlopenflags() -- set the flags to be used for dlopen() calls
175 #setdlopenflags()——设置用于dlopen()调用的标志
176
177 setprofile() -- set the global profiling function
178 #setprofile()——设置全局配置函数
179
180 setrecursionlimit() -- set the max recursion depth for the interpreter
181 #setrecursionlimit()——设置解释器的最大递归深度
182
183 settrace() -- set the global debug tracing function
184 #settrace()——设置全局调试跟踪函数
185 """
186 # no imports
187
188 # Variables with simple values
189
190 api_version = 1013
191
192 base_exec_prefix = 'C:\\Users\\lenovo\\AppData\\Local\\Programs\\Python\\Python37'
193
194 base_prefix = 'C:\\Users\\lenovo\\AppData\\Local\\Programs\\Python\\Python37'
195
196 byteorder = 'little'
197
198 copyright = 'Copyright (c) 2001-2018 Python Software Foundation.\nAll Rights Reserved.\n\nCopyright (c) 2000 BeOpen.com.\nAll Rights Reserved.\n\nCopyright (c) 1995-2001 Corporation for National Research Initiatives.\nAll Rights Reserved.\n\nCopyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.\nAll Rights Reserved.'
199
200 dllhandle = 140718339260416
201
202 dont_write_bytecode = True
203
204 executable = 'C:\\Users\\lenovo\\AppData\\Local\\Programs\\Python\\Python37\\python.exe'
205
206 exec_prefix = 'C:\\Users\\lenovo\\AppData\\Local\\Programs\\Python\\Python37'
207
208 float_repr_style = 'short'
209
210 hexversion = 50790640
211
212 maxsize = 9223372036854775807
213 maxunicode = 1114111
214
215 platform = 'win32'
216
217 prefix = 'C:\\Users\\lenovo\\AppData\\Local\\Programs\\Python\\Python37'
218
219 version = '3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)]'
220
221 winver = '3.7'
222
223 _framework = ''
224
225 _home = None
226
227
228 # functions
229
230 def breakpointhook(*args, **kws):
231     # real signature unknown; restored from __doc__
232     #真正的签名未知;恢复从__doc__
233     """
234     breakpointhook(*args, **kws)
235     This hook function is called by built-in breakpoint().
236     #这个钩子函数由内置的断点breakpoint()调用。
237     """
238     pass
239
240
241 def callstats():  # real signature unknown; restored from __doc__
242     """
243     callstats() -> tuple of integers
244     Return a tuple of function call statistics, if CALL_PROFILE was defined
245     when Python was built.  Otherwise, return None.
246     When enabled, this function returns detailed, implementation-specific
247     details about the number of function calls executed. The return value is
248     a 11-tuple where the entries in the tuple are counts of:
249     0. all function calls
250     1. calls to PyFunction_Type objects
251     2. PyFunction calls that do not create an argument tuple
252     3. PyFunction calls that do not create an argument tuple
253        and bypass PyEval_EvalCodeEx()
254     4. PyMethod calls
255     5. PyMethod calls on bound methods
256     6. PyType calls
257     7. PyCFunction calls
258     8. generator calls
259     9. All other calls
260     10. Number of stack pops performed by call_function()
261     """
262     # callstats() ->整数元组返回一个函数调用统计数据元组,如果在构建Python时定义了
263     # CALL_PROFILE的话。否则,返回None。当启用时,该函数返回关于执行的函数调用数量的详细
264     # 的、特定于实现的详细信息。返回值是一个11元组,其中元组中的条目的计数为:
265     # 0。所有的函数调用
266     # 1。调用PyFunction_Type对象
267     # 2。不创建参数元组的PyFunction调用
268     # 3。不创建参数tuple和绕过PyEval_EvalCodeEx()的PyFunction调用
269     # 4。PyMethod调用
270     # 5。PyMethod调用绑定方法
271     # 6。PyType调用
272     # 7。PyCFunction调用
273     # 8。发电机的电话
274     # 9。所有其他的电话
275     # 10。call_function()执行的堆栈pop数
276     return ()
277
278
279 def call_tracing(func, args):  # real signature unknown; restored from __doc__
280     """
281     call_tracing(func, args) -> object
282     Call func(*args), while tracing is enabled.  The tracing state is
283     saved, and restored afterwards.  This is intended to be called from
284     a debugger from a checkpoint, to recursively debug some other code.
285     """
286     #call_tracking (func, args) ->对象调用func(*args),同时启用跟踪。保存跟踪状态,
287     # 然后恢复跟踪状态。这是为了从检查点从调试器调用,以递归地调试其他代码。
288     return object()
289
290
291 def displayhook(p_object):  # real signature unknown; restored from __doc__
292     """
293     displayhook(object) -> None
294     Print an object to sys.stdout and also save it in builtins._
295     """
296     #没有打印一个对象给sys。并保存在build ._中
297     pass
298
299
300 def excepthook(exctype, value, traceback):  # real signature unknown; restored from __doc__
301     """
302     excepthook(exctype, value, traceback) -> None
303     Handle an exception by displaying it with a traceback on sys.stderr.
304     """
305     #异常(excthook, value, traceback) -> None通过在sys.stderr上显示它来处理异常。
306     pass
307
308
309 def exc_info():  # real signature unknown; restored from __doc__
310     """
311     exc_info() -> (type, value, traceback)
312     Return information about the most recent exception caught by an except
313     clause in the current stack frame or in an older stack frame.
314     """
315     #ex_info() ->(类型、值、回溯)返回当前栈帧或旧栈帧中except子句捕获的最新异常的信息。
316     pass
317
318
319 def exit(status=None):  # real signature unknown; restored from __doc__
320     """
321     exit([status])
322     Exit the interpreter by raising SystemExit(status).
323     If the status is omitted or None, it defaults to zero (i.e., success).
324     If the status is an integer, it will be used as the system exit status.
325     If it is another kind of object, it will be printed and the system
326     exit status will be one (i.e., failure).
327     #通过提升SystemExit(status)退出解释器。如果状态被省略或没有,它默认为0(即成功)。
328     如果状态是整数,它将用作系统退出状态。如果它是另一种对象,它将被打印和系统
329     退出状态为1(即,失败)。
330     """
331     pass
332
333
334 def getallocatedblocks():  # real signature unknown; restored from __doc__
335     """
336     getallocatedblocks() -> integer
337     Return the number of memory blocks currently allocated, regardless of their
338     size.
339     """
340     #getallocatedblocks()——>整数返回当前分配的内存块的数量,而不管它们的大小。
341     return 0
342
343
344 def getcheckinterval():  # real signature unknown; restored from __doc__
345     """ getcheckinterval() -> current check interval; see setcheckinterval(). """
346     #getcheckinterval() ->当前检查间隔;看到setcheckinterval ()。
347     pass
348
349
350 def getdefaultencoding():  # real signature unknown; restored from __doc__
351     """
352     getdefaultencoding() -> string
353     Return the current default string encoding used by the Unicode
354     implementation.
355     """
356     #返回Unicode实现使用的当前默认字符串编码。
357     return ""
358
359
360 def getfilesystemencodeerrors():  # real signature unknown; restored from __doc__
361     """
362     getfilesystemencodeerrors() -> string
363     Return the error mode used to convert Unicode filenames in
364     operating system filenames.
365     """
366     #返回用于转换操作系统文件名中的Unicode文件名的错误模式。
367     return ""
368
369
370 def getfilesystemencoding():  # real signature unknown; restored from __doc__
371     """
372     getfilesystemencoding() -> string
373     Return the encoding used to convert Unicode filenames in
374     operating system filenames.
375     """
376     #返回用于转换操作系统文件名中的Unicode文件名的编码。
377     return ""
378
379
380 def getprofile():  # real signature unknown; restored from __doc__
381     """
382     getprofile()
383     Return the profiling function set with sys.setprofile.
384     See the profiler chapter in the library manual.
385     """
386     #getprofile()返回带有sys.setprofile的分析函数集。请参阅库手册中的profiler一章。
387     pass
388
389
390 def getrecursionlimit():  # real signature unknown; restored from __doc__
391     """
392     getrecursionlimit()
393     Return the current value of the recursion limit, the maximum depth
394     of the Python interpreter stack.  This limit prevents infinite
395     recursion from causing an overflow of the C stack and crashing Python.
396     """
397     #getrecursionlimit()返回递归限制的当前值,即Python解释器堆栈的最大深度。这个限制
398     # 可以防止无限递归导致C堆栈溢出和Python崩溃。
399     pass
400
401
402 def getrefcount(p_object):  # real signature unknown; restored from __doc__
403     """
404     getrefcount(object) -> integer
405     Return the reference count of object.  The count returned is generally
406     one higher than you might expect, because it includes the (temporary)
407     reference as an argument to getrefcount().
408     """
409     #返回对象的引用计数。返回的计数通常比您预期的要高,因为它包含(临时)引用作为
410     # getrefcount()的参数。
411     return 0
412
413
414 def getsizeof(p_object, default):  # real signature unknown; restored from __doc__
415     """
416     getsizeof(object, default) -> int
417     Return the size of object in bytes.
418     """
419     #返回对象的大小(以字节为单位)
420     return 0
421
422
423 def getswitchinterval():  # real signature unknown; restored from __doc__
424     """ getswitchinterval() -> current thread switch interval; see setswitchinterval(). """
425     #当前线程切换间隔;看到setswitchinterval ()。
426     pass
427
428
429 def gettrace():  # real signature unknown; restored from __doc__
430     """
431     gettrace()
432     Return the global debug tracing function set with sys.settrace.
433     See the debugger chapter in the library manual.
434     """
435     #gettrace()用sys.settrace返回全局调试跟踪函数集。请参阅库手册中的调试器一章
436     pass
437
438
439 def getwindowsversion():  # real signature unknown; restored from __doc__
440     """
441     getwindowsversion()
442     Return information about the running version of Windows as a named tuple.
443     The members are named: major, minor, build, platform, service_pack,
444     service_pack_major, service_pack_minor, suite_mask, and product_type. For
445     backward compatibility, only the first 5 items are available by indexing.
446     All elements are numbers, except service_pack and platform_type which are
447     strings, and platform_version which is a 3-tuple. Platform is always 2.
448     Product_type may be 1 for a workstation, 2 for a domain controller, 3 for a
449     server. Platform_version is a 3-tuple containing a version number that is
450     intended for identifying the OS rather than feature detection.
451     """
452     #getwindowsversion()以命名元组的形式返回关于Windows运行版本的信息。成员命名
453     # 为:major、minor、build、platform、service_pack、service_pack_major、
454     # service_pack_minor、suite_mask和product_type。为了向后兼容,只有前5项可以通过
455     # 索引获得。所有元素都是数字,除了service_pack和platform_type是字符串,
456     # platform_version是3元组。平台总是2。Product_type对于工作站可能是1,对于域控制器
457     # 可能是2,对于服务器可能是3。Platform_version是一个包含版本号的三元组,用于识别操作
458     # 系统而不是功能检测。
459     pass
460
461
462 def get_asyncgen_hooks():  # real signature unknown; restored from __doc__
463     """
464     get_asyncgen_hooks()
465     Return a namedtuple of installed asynchronous generators hooks (firstiter, finalizer).
466     """
467     #get_asyncgen_hooks()返回一个已安装的异步生成器挂钩的命名元组(firstiter, finalizer)。
468     pass
469
470
471 def get_coroutine_origin_tracking_depth(*args, **kwargs):  # real signature unknown
472     """ Check status of origin tracking for coroutine objects in this thread. """
473     #检查此线程中协程对象的原点跟踪状态。
474     pass
475
476
477 def get_coroutine_wrapper():  # real signature unknown; restored from __doc__
478     """
479     get_coroutine_wrapper()
480     Return the wrapper for coroutine objects set by sys.set_coroutine_wrapper.
481     """
482     #get_coroutine_wrapper()返回sys.set_coroutine_wrapper所设置的coroutine对象的包装器。
483     pass
484
485
486 def intern(string):  # real signature unknown; restored from __doc__
487     """
488     intern(string) -> string
489     ``Intern'' the given string.  This enters the string in the (global)
490     table of interned strings whose purpose is to speed up dictionary lookups.
491     Return the string itself or the previously interned string object with the
492     same value.
493     """
494     #intern(string) -> string``Intern'' the given string.这将进入interned字符串
495     # (全局)表中的字符串,其目的是加速字典查找。返回具有相同值的字符串本身或先前嵌入的
496     # 字符串对象。
497     return ""
498
499
500 def is_finalizing():  # real signature unknown; restored from __doc__
501     """
502     is_finalizing()
503     Return True if Python is exiting.
504     """
505     #如果Python退出,is_finalizing()返回True。
506     pass
507
508
509 def setcheckinterval(n):  # real signature unknown; restored from __doc__
510     """
511     setcheckinterval(n)
512     Tell the Python interpreter to check for asynchronous events every
513     n instructions.  This also affects how often thread switches occur.
514     """
515     #setcheckinterval(n)告诉Python解释器在每n条指令中检查异步事件。这也会影响线程切换的频率
516     pass
517
518
519 def setprofile(function):  # real signature unknown; restored from __doc__
520     """
521     setprofile(function)
522     Set the profiling function.  It will be called on each function call
523     and return.  See the profiler chapter in the library manual.
524     """
525     #设置配置函数。它将在每个函数调用和返回时被调用。请参阅库手册中的profiler一章。
526     pass
527
528
529 def setrecursionlimit(n):  # real signature unknown; restored from __doc__
530     """
531     setrecursionlimit(n)
532     Set the maximum depth of the Python interpreter stack to n.  This
533     limit prevents infinite recursion from causing an overflow of the C
534     stack and crashing Python.  The highest possible limit is platform-
535     dependent.
536     """
537     #setrecursionlimit(n)设置Python解释器堆栈的最大深度为n。这个限制可以防止无限递归
538     # 导致C堆栈溢出和Python崩溃。最大的可能极限是平台相关的。
539     pass
540
541
542 def setswitchinterval(n):  # real signature unknown; restored from __doc__
543     """
544     setswitchinterval(n)
545     Set the ideal thread switching delay inside the Python interpreter
546     The actual frequency of switching threads can be lower if the
547     interpreter executes long sequences of uninterruptible code
548     (this is implementation-specific and workload-dependent).
549     The parameter must represent the desired switching delay in seconds
550     A typical value is 0.005 (5 milliseconds).
551     """
552     #在Python解释器中设置理想的线程切换延迟,如果解释器执行不间断代码的长序列(这是具体
553     # 实现和工作负载相关的),切换线程的实际频率可能会更低。参数必须表示所需的切换延迟
554     # (以秒为单位),典型值为0.005(5毫秒)。
555     pass
556
557
558 def settrace(function):  # real signature unknown; restored from __doc__
559     """
560     settrace(function)
561     Set the global debug tracing function.  It will be called on each
562     function call.  See the debugger chapter in the library manual.
563     """
564     #设置全局调试跟踪函数。它将在每次函数调用时被调用。请参阅库手册中的调试器一章。
565     pass
566
567
568 def set_asyncgen_hooks(*args, **kwargs):  # real signature unknown; NOTE: unreliably restored from __doc__
569     """
570     set_asyncgen_hooks(*, firstiter=None, finalizer=None)
571     Set a finalizer for async generators objects.
572     """
573     #set_asyncgen_hooks(*, firstiter=None, finalizer=None)为异步生成器对象设置一个终结器。
574     pass
575
576
577 def set_coroutine_origin_tracking_depth(*args, **kwargs):  # real signature unknown
578     """
579     Enable or disable origin tracking for coroutine objects in this thread.
580     Coroutine objects will track 'depth' frames of traceback information about
581     where they came from, available in their cr_origin attribute. Set depth of 0
582     to disable.
583     """
584     #在此线程中启用或禁用协程对象的原点跟踪。协同程序对象将跟踪关于它们来自何处的回溯信息
585     # 的“深度”帧,这些信息可以在它们的cr_origin属性中找到。设置深度为0以禁用。
586     pass
587
588
589 def set_coroutine_wrapper(wrapper):  # real signature unknown; restored from __doc__
590     """
591     set_coroutine_wrapper(wrapper)
592     Set a wrapper for coroutine objects.
593     """
594     #为协程对象设置一个包装器。
595     pass
596
597
598 def _clear_type_cache():  # real signature unknown; restored from __doc__
599     """
600     _clear_type_cache() -> None
601     Clear the internal type lookup cache.
602     """
603     #清除内部类型查找缓存。
604     pass
605
606
607 def _current_frames():  # real signature unknown; restored from __doc__
608     """
609     _current_frames() -> dictionary
610     Return a dictionary mapping each current thread T's thread id to T's
611     current stack frame.
612     This function should be used for specialized purposes only.
613     """
614     #返回一个将每个当前线程T的线程id映射到T的当前堆栈帧的字典。此函数只应用于专门用途。
615     return {}
616
617
618 def _debugmallocstats():  # real signature unknown; restored from __doc__
619     """
620     _debugmallocstats()
621     Print summary info to stderr about the state of
622     pymalloc's structures.
623     In Py_DEBUG mode, also perform some expensive internal consistency
624     checks.
625     """
626     #模式下,还要执行一些昂贵的内部一致性检查。
627     pass
628
629
630 def _enablelegacywindowsfsencoding():  # real signature unknown; restored from __doc__
631     """
632     _enablelegacywindowsfsencoding()
633     Changes the default filesystem encoding to mbcs:replace for consistency
634     with earlier versions of Python. See PEP 529 for more information.
635     This is equivalent to defining the PYTHONLEGACYWINDOWSFSENCODING
636     environment variable before launching Python.
637     """
638     #_enablelegacywindowsfsencoding()将默认的文件系统编码更改为mbcs:替换为与早期
639     # Python版本的一致性。有关更多信息,请参见PEP 529。这相当于在启动Python之前定义
640     # PYTHONLEGACYWINDOWSFSENCODING环境变量。
641     pass
642
643
644 def _getframe(depth=None):  # real signature unknown; restored from __doc__
645     """
646     _getframe([depth]) -> frameobject
647     Return a frame object from the call stack.  If optional integer depth is
648     given, return the frame object that many calls below the top of the stack.
649     If that is deeper than the call stack, ValueError is raised.  The default
650     for depth is zero, returning the frame at the top of the call stack.
651     This function should be used for internal and specialized
652     purposes only.
653     """
654     #bb0 frameobject从调用堆栈返回一个框架对象。如果给定了可选的整数深度,则返回堆栈顶
655     # 部下面许多调用的框架对象。如果这比调用堆栈更深,则会引发ValueError。depth的默认值
656     # 为0,返回调用堆栈顶部的框架。此功能应仅用于内部和专门用途。
657     pass
658
659
660 def __breakpointhook__(*args, **kwargs):  # real signature unknown
661     """
662     breakpointhook(*args, **kws)
663     This hook function is called by built-in breakpoint().
664     """
665     #breakpointhook(*args, **kws)这个钩子函数是由内置的breakpoint()调用的。
666     pass
667
668
669 def __displayhook__(*args, **kwargs):  # real signature unknown
670     """
671     displayhook(object) -> None
672     Print an object to sys.stdout and also save it in builtins._
673     """
674     #没有打印一个对象给sys。并保存在build ._中
675     pass
676
677
678 def __excepthook__(*args, **kwargs):  # real signature unknown
679     """
680     excepthook(exctype, value, traceback) -> None
681     Handle an exception by displaying it with a traceback on sys.stderr.
682     """
683     #通过在sys.stderr上显示一个回溯来处理异常。
684     pass
685
686
687 def __interactivehook__():  # reliably restored by inspect
688     # no doc
689     pass
690
691
692 # classes
693
694 class __loader__(object):
695     """
696     Meta path import for built-in modules
697     All methods are either class or static methods to avoid the need to
698     instantiate the class.
699     """
700     #内建模块的元路径导入所有方法都是类或静态方法,以避免需要实例化类。
701
702     @classmethod
703     def create_module(cls, *args, **kwargs):  # real signature unknown
704         """ Create a built-in module """
705         pass
706
707     @classmethod
708     def exec_module(cls, *args, **kwargs):  # real signature unknown
709         """ Exec a built-in module """
710         #执行一个内置模块
711         pass
712
713     @classmethod
714     def find_module(cls, *args, **kwargs):  # real signature unknown
715         """
716         Find the built-in module.
717         If 'path' is ever specified then the search is considered a failure.
718         This method is deprecated.  Use find_spec() instead.
719         """
720         #找到内置模块。如果指定了“path”,则认为搜索失败。这种方法不赞成使用。使用find_spec ()
721         pass
722
723     @classmethod
724     def find_spec(cls, *args, **kwargs):  # real signature unknown
725         pass
726
727     @classmethod
728     def get_code(cls, *args, **kwargs):  # real signature unknown
729         """ Return None as built-in modules do not have code objects. """
730         #返回None,因为内置模块没有代码对象。
731         pass
732
733     @classmethod
734     def get_source(cls, *args, **kwargs):  # real signature unknown
735         """ Return None as built-in modules do not have source code. """
736         #没有返回作为内置模块没有源代码
737         pass
738
739     @classmethod
740     def is_package(cls, *args, **kwargs):  # real signature unknown
741         """ Return False as built-in modules are never packages. """
742         #返回False,因为内置模块从来不是包
743         pass
744
745     @classmethod
746     def load_module(cls, *args, **kwargs):  # real signature unknown
747         """
748         Load the specified module into sys.modules and return it.
749         This method is deprecated.  Use loader.exec_module instead.
750         """
751         #将指定的模块加载到sys中。模块并返回它。这种方法不赞成使用。使用加载程序。exec_module代替。
752         pass
753
754     def module_repr(module):  # reliably restored by inspect
755         """
756         Return repr for the module.
757         The method is deprecated.  The import machinery does the job itself.
758         """
759         #返回模块的repr。该方法不赞成使用。进口机器自己完成这项工作。
760         pass
761
762     def __init__(self, *args, **kwargs):  # real signature unknown
763         pass
764
765     __weakref__ = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
766     """list of weak references to the object (if defined)"""
767
768     __dict__ = None  # (!) real value is ''
769
770
771 # variables with complex values
772
773 argv = []  # real value of type <class 'list'> skipped
774
775 builtin_module_names = ()  # real value of type <class 'tuple'> skipped
776
777 flags = (
778     0,
779     0,
780     0,
781     0,
782     1,
783     0,
784     0,
785     0,
786     0,
787     0,
788     0,
789     1,
790     0,
791     False,
792     0,
793 )
794
795 float_info = (
796     1.7976931348623157e+308,
797     1024,
798     308,
799     2.2250738585072014e-308,
800     -1021,
801     -307,
802     15,
803     53,
804     2.220446049250313e-16,
805     2,
806     1,
807 )
808
809 hash_info = (
810     64,
811     2305843009213693951,
812     314159,
813     0,
814     1000003,
815     'siphash24',
816     64,
817     128,
818     0,
819 )
820
821 implementation = None  # (!) real value is ''
822
823 int_info = (
824     30,
825     4,
826 )
827
828 meta_path = [
829     __loader__,
830     None,  # (!) real value is ''
831     None,  # (!) real value is ''
832 ]
833
834 modules = {}  # real value of type <class 'dict'> skipped
835
836 path = [
837     'C:\\Program Files\\JetBrains\\PyCharm Community Edition 2018.1.4\\helpers',
838     'C:\\Users\\lenovo\\AppData\\Local\\Programs\\Python\\Python37\\python37.zip',
839     'C:\\Users\\lenovo\\AppData\\Local\\Programs\\Python\\Python37\\DLLs',
840     'C:\\Users\\lenovo\\AppData\\Local\\Programs\\Python\\Python37\\lib',
841     'C:\\Users\\lenovo\\AppData\\Local\\Programs\\Python\\Python37',
842     'C:\\Users\\lenovo\\AppData\\Local\\Programs\\Python\\Python37\\lib\\site-packages',
843 ]
844
845 path_hooks = [
846     None,  # (!) real value is ''
847     None,  # (!) real value is ''
848 ]
849
850 path_importer_cache = {}  # real value of type <class 'dict'> skipped
851
852 stderr = None  # (!) real value is ''
853
854 stdin = None  # (!) forward: __stdin__, real value is ''
855
856 stdout = None  # (!) forward: __stdout__, real value is ''
857
858 thread_info = (
859     'nt',
860     None,
861     None,
862 )
863
864 version_info = (
865     3,
866     7,
867     0,
868     'final',
869     0,
870 )
871
872 warnoptions = []
873
874 _git = (
875     'CPython',
876     'v3.7.0',
877     '1bf9cc5093',
878 )
879
880 _xoptions = {}
881
882 __spec__ = None  # (!) real value is ''
883
884 __stderr__ = stderr
885
886 __stdin__ = None  # (!) real value is ''
887
888 __stdout__ = None  # (!) real value is ''
889
890 # intermittent names
891 exc_value = Exception()
892 exc_traceback = None
sys源代码.py
  • time模块
'''time模块:'''
#从1970年开始 到当前时间(时间戳)
import time
print(time.time())

#时区  夏令时:白天多出两天
import time
print(time.localtime())

#中国:东八区
import time
print(time.timezone)

#夏令时
import time
print(time.daylight)

#程序停止几秒
import time
print(time.sleep(8))

#年、月、日、时、分、秒、夏令时
import time
print(time.gmtime())

#进行格式化转换
import time
x = time.localtime()
print(time.strftime("%Y-%m-%d %H:%M:%S",x))

#将格式化字符串变成元组形式
import time
print(time.strptime("2018-11-4 11:04:34","%Y-%m-%d %H:%M:%S"))

'''Python time asctime()
函数接受时间元组并返回一个可读的形式为
Tue Dec 11 18:07:14 2008
(2008年12月11日 周二18时07分14秒)的24个字符的字符串
把一个表示时间的元组或者struct_time表示为这种形式:
'Sun Jun 20 23:21:05 1993'。
如果没有参数,将会将time.localtime()作为参数传入。
print(time.asctime())
'''
#国际标准时间格式
import time
print(time.asctime((2018,11,4,11,4,34,2,227,-1)))

'''
time.ctime([secs]):
把一个时间戳(按秒计算的浮点数)转化为time.asctime()的形式。
如果参数未给或者为None的时候,将会默认time.time()为参数。
它的作用相当于time.asctime(time.localtime(secs))
'''
#浮点数的秒数
import time
print(time.ctime(5635512.2))
print(time.ctime())
Python   模块-LMLPHPPython   模块-LMLPHP
  1 # encoding: utf-8
  2 # module time
  3 # from (built-in)
  4 # by generator 1.145
  5 """
  6 This module provides various functions to manipulate time values.
  7
  8 There are two standard representations of time.  One is the number
  9 of seconds since the Epoch, in UTC (a.k.a. GMT).  It may be an integer
 10 or a floating point number (to represent fractions of seconds).
 11 The Epoch is system-defined; on Unix, it is generally January 1st, 1970.
 12 The actual value can be retrieved by calling gmtime(0).
 13
 14 The other representation is a tuple of 9 integers giving local time.
 15 The tuple items are:
 16   year (including century, e.g. 1998)
 17   month (1-12)
 18   day (1-31)
 19   hours (0-23)
 20   minutes (0-59)
 21   seconds (0-59)
 22   weekday (0-6, Monday is 0)
 23   Julian day (day in the year, 1-366)
 24   DST (Daylight Savings Time) flag (-1, 0 or 1)
 25 If the DST flag is 0, the time is given in the regular time zone;
 26 if it is 1, the time is given in the DST time zone;
 27 if it is -1, mktime() should guess based on the date and time.
 28 """
 29 #这个模块提供了各种操作时间值的函数。时间有两种标准表示方式。一个是自纪元以来的秒数,
 30 # 用UTC表示。它可以是整数或浮点数(表示秒的小数)。时代是系统定义的;在Unix上,
 31 # 通常是1970年1月1日。实际值可以通过调用gmtime(0)来检索。
 32 # 另一种表示是一个由9个整数组成的元组,提供本地时间。元组项目有:
 33 #年份(包括世纪,例如1998年)
 34 #月(1 - 12)
 35 #天(1 - 31)
 36 #小时(0-23)
 37 #分钟(0-59)
 38 #秒(0-59)
 39 #星期一(0-6日,星期一0日)
 40 #儒略日(一年中的一天,1-366)
 41 #DST(夏令时)标志(-1,0或1)如果DST标志为0,时间在常规时区给出;如果是1,时间在DST时区
 42 # 给出;如果是-1,mktime()应该根据日期和时间猜测。
 43
 44
 45 # no imports
 46
 47 # Variables with simple values  #带有简单值的变量
 48
 49 altzone = -32400
 50
 51 daylight = 0
 52
 53 timezone = -28800
 54
 55 _STRUCT_TM_ITEMS = 11
 56
 57
 58 # functions
 59
 60 def asctime(p_tuple=None):  # real signature unknown; restored from __doc__
 61     """
 62     asctime([tuple]) -> string
 63
 64     Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.
 65     When the time tuple is not present, current time as returned by localtime()
 66     is used.
 67     """
 68     #将时间元组转换为字符串。“1998年6月06日星期六16:26:11”。当time元组不存在时,
 69     # 使用localtime()返回的当前时间。
 70     return ""
 71
 72
 73 def clock():  # real signature unknown; restored from __doc__
 74     """
 75     clock() -> floating point number
 76
 77     Return the CPU time or real time since the start of the process or since
 78     the first call to clock().  This has as much precision as the system
 79     records.
 80     """
 81     #返回进程开始或第一次调用clock()以来的CPU时间或实时时间。这与系统记录一样精确。
 82     return 0.0
 83
 84
 85 def ctime(seconds=None):  # known case of time.ctime
 86     """
 87     ctime(seconds) -> string
 88
 89     Convert a time in seconds since the Epoch to a string in local time.
 90     This is equivalent to asctime(localtime(seconds)). When the time tuple is
 91     not present, current time as returned by localtime() is used.
 92     """
 93     #将纪元以来的时间(以秒为单位)转换为本地时间的字符串。这相当于
 94     #asctime(localtime(seconds))。当time元组不存在时,使用localtime()返回的当前时间。
 95     return ""
 96
 97
 98 def get_clock_info(name):  # real signature unknown; restored from __doc__
 99     """
100     get_clock_info(name: str) -> dict
101
102     Get information of the specified clock.
103     """
104     #获取指定时钟的信息。
105     return {}
106
107
108 def gmtime(seconds=None):  # real signature unknown; restored from __doc__
109     """
110     gmtime([seconds]) -> (tm_year, tm_mon, tm_mday, tm_hour, tm_min,
111                            tm_sec, tm_wday, tm_yday, tm_isdst)
112
113     Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.
114     GMT).  When 'seconds' is not passed in, convert the current time instead.
115
116     If the platform supports the tm_gmtoff and tm_zone, they are available as
117     attributes only.
118     """
119     #将大纪元以来的秒转换为表示UTC(即格林尼治时间)的时间元组。如果没有传入“秒”,
120     # 则转换当前时间。如果平台支持tm_gmtoff和tm_zone,那么它们只能作为属性使用。
121     pass
122
123
124 def localtime(seconds=None):  # real signature unknown; restored from __doc__
125     """
126     localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,
127                               tm_sec,tm_wday,tm_yday,tm_isdst)
128
129     Convert seconds since the Epoch to a time tuple expressing local time.
130     When 'seconds' is not passed in, convert the current time instead.
131     """
132     #将大纪元以来的秒转换为表示本地时间的时间元组。如果没有传入“秒”,则转换当前时间。
133     pass
134
135
136 def mktime(p_tuple):  # real signature unknown; restored from __doc__
137     """
138     mktime(tuple) -> floating point number
139
140     Convert a time tuple in local time to seconds since the Epoch.
141     Note that mktime(gmtime(0)) will not generally return zero for most
142     time zones; instead the returned value will either be equal to that
143     of the timezone or altzone attributes on the time module.
144     """
145     #mktime(元组)->浮点数
146     # 将本地时间中的时间元组转换为秒,因为Epoch提示mktime(gmtime(0))通常不会为
147     # mos时区返回零;相反,返回的值将等于time模块上的时区属性或altzone属性的值。
148     return 0.0
149
150
151 def monotonic():  # real signature unknown; restored from __doc__
152     """
153     monotonic() -> float
154
155     Monotonic clock, cannot go backward.
156     """
157     #单调的时钟,不能倒转。
158     return 0.0
159
160
161 def monotonic_ns():  # real signature unknown; restored from __doc__
162     """
163     monotonic_ns() -> int
164
165     Monotonic clock, cannot go backward, as nanoseconds.
166     """
167     #单调时钟,不能像纳秒那样倒转。
168     return 0
169
170
171 def perf_counter():  # real signature unknown; restored from __doc__
172     """
173     perf_counter() -> float
174
175     Performance counter for benchmarking.
176     """
177     #性能计数器用于基准测试。
178     return 0.0
179
180
181 def perf_counter_ns():  # real signature unknown; restored from __doc__
182     """
183     perf_counter_ns() -> int
184
185     Performance counter for benchmarking as nanoseconds.
186     """
187     #性能计数器,用于基准测试为纳秒。
188     return 0
189
190
191 def process_time():  # real signature unknown; restored from __doc__
192     """
193     process_time() -> float
194
195     Process time for profiling: sum of the kernel and user-space CPU time.
196     """
197     #分析的进程时间:内核和用户空间CPU时间的总和。
198     return 0.0
199
200
201 def process_time_ns(*args, **kwargs):  # real signature unknown
202     """
203     process_time() -> int
204
205     Process time for profiling as nanoseconds:
206     sum of the kernel and user-space CPU time.
207     """
208     #用于分析纳秒的进程时间:内核和用户空间CPU时间的总和。
209     pass
210
211
212 def sleep(seconds):  # real signature unknown; restored from __doc__
213     """
214     sleep(seconds)
215
216     Delay execution for a given number of seconds.  The argument may be
217     a floating point number for subsecond precision.
218     """
219     #对给定的秒数延迟执行。参数可以是次秒精度的浮点数
220     pass
221
222
223 def strftime(format, p_tuple=None):  # real signature unknown; restored from __doc__
224     """
225     strftime(format[, tuple]) -> string
226
227     Convert a time tuple to a string according to a format specification.
228     See the library reference manual for formatting codes. When the time tuple
229     is not present, current time as returned by localtime() is used.
230     #根据格式规范将时间元组转换为字符串。有关格式化代码的库参考手册。
231     当time元组不存在时,使用localtime()返回的当前时间
232
233     Commonly used format codes:
234
235     %Y  Year with century as a decimal number.
236     %m  Month as a decimal number [01,12].
237     %d  Day of the month as a decimal number [01,31].
238     %H  Hour (24-hour clock) as a decimal number [00,23].
239     %M  Minute as a decimal number [00,59].
240     %S  Second as a decimal number [00,61].
241     %z  Time zone offset from UTC.
242     %a  Locale's abbreviated weekday name.
243     %A  Locale's full weekday name.
244     %b  Locale's abbreviated month name.
245     %B  Locale's full month name.
246     %c  Locale's appropriate date and time representation.
247     %I  Hour (12-hour clock) as a decimal number [01,12].
248     %p  Locale's equivalent of either AM or PM.
249
250     Other codes may be available on your platform.  See documentation for
251     the C library strftime function.
252     #在您的平台上可以使用其他代码。请参阅C库strftime函数的文档。
253     """
254     return ""
255
256
257 def strptime(string, format):  # real signature unknown; restored from __doc__
258     """
259     strptime(string, format) -> struct_time
260
261     Parse a string to a time tuple according to a format specification.
262     See the library reference manual for formatting codes (same as
263     strftime()).
264
265     Commonly used format codes:
266
267     %Y  Year with century as a decimal number.
268     %m  Month as a decimal number [01,12].
269     %d  Day of the month as a decimal number [01,31].
270     %H  Hour (24-hour clock) as a decimal number [00,23].
271     %M  Minute as a decimal number [00,59].
272     %S  Second as a decimal number [00,61].
273     %z  Time zone offset from UTC.
274     %a  Locale's abbreviated weekday name.
275     %A  Locale's full weekday name.
276     %b  Locale's abbreviated month name.
277     %B  Locale's full month name.
278     %c  Locale's appropriate date and time representation.
279     %I  Hour (12-hour clock) as a decimal number [01,12].
280     %p  Locale's equivalent of either AM or PM.
281
282     Other codes may be available on your platform.  See documentation for
283     the C library strftime function.
284     """
285     #strptime(字符串,格式)-> struct_time
286     #根据格式规范将字符串解析为时间元组。有关格式化代码(与strftime()相同),请参阅库参考手册。
287
288     #常用格式代码:
289     #% Y: 以世纪为十进制的年份。
290     #% m: 月份为十进制数[01, 12]。
291     #% d: 以小数形式表示的月份日[01, 31]。
292     #% H: 小时(24小时时钟)作为小数[00, 23]。
293     #% M: 分钟作为小数[00, 59]。
294     #% S: 作为小数的秒[00, 61]。
295     #% z: 世界时偏移距。
296     #% a:本地语言环境的缩写的工作日名称。
297     #% A:本地语言环境的完整工作日名称。
298     #% b: Locale的缩写名。
299     #% B: Locale的全名。
300     #% c: 语言环境的适当日期和时间表示。
301     #% I: Hour(12小时时钟)作为小数[01, 12]。
302     #% p: 现场相当于上午或下午。
303     #在您的平台上可以使用其他代码。请参阅C库strftime函数的文档
304     return struct_time
305
306
307 def thread_time():  # real signature unknown; restored from __doc__
308     """
309     thread_time() -> float
310
311     Thread time for profiling: sum of the kernel and user-space CPU time.
312     """
313     #用于分析的线程时间:内核和用户空间CPU时间的总和。
314     return 0.0
315
316
317 def thread_time_ns(*args, **kwargs):  # real signature unknown
318     """
319     thread_time() -> int
320
321     Thread time for profiling as nanoseconds:
322     sum of the kernel and user-space CPU time.
323     """
324     #用于分析纳秒的线程时间:内核和用户空间CPU时间的总和。
325     pass
326
327
328 def time():  # real signature unknown; restored from __doc__
329     """
330     time() -> floating point number
331
332     Return the current time in seconds since the Epoch.
333     Fractions of a second may be present if the system clock provides them.
334     """
335     #以秒为单位返回纪元以来的当前时间。如果系统时钟提供了几分之一秒的时间,那么可能会出现这种情况。
336     return 0.0
337
338
339 def time_ns():  # real signature unknown; restored from __doc__
340     """
341     time_ns() -> int
342
343     Return the current time in nanoseconds since the Epoch.
344     """
345     #返回纪元以来的当前时间(以纳秒为单位)。
346     return 0
347
348
349 # classes
350
351 class struct_time(tuple):
352     """
353     The time value as returned by gmtime(), localtime(), and strptime(), and
354      accepted by asctime(), mktime() and strftime().  May be considered as a
355      sequence of 9 integers.
356      Note that several fields' values are not the same as those defined by
357      the C language standard for struct tm.  For example, the value of the
358      field tm_year is the actual year, not year - 1900.  See individual
359      fields' descriptions for details.
360     """
361     #由gmtime()、localtime()和strptime()返回并被asctime()、mktime()和strftime()
362     # 接受的时间值。可以认为是9个整数的序列。注意,几个字段的值与struct tm的C语言
363     # 标准定义的值不相同。例如,字段tm_year的值是实际年份,而不是年- 1900。有关详细
364     # 信息,请参阅各个字段的说明。
365
366     def __init__(self, *args, **kwargs):  # real signature unknown
367         pass
368
369     @staticmethod  # known case of __new__
370     def __new__(*args, **kwargs):  # real signature unknown
371         """ Create and return a new object.  See help(type) for accurate signature. """
372         #创建并返回一个新对象。请参阅帮助(类型)以获得准确的签名。
373         pass
374
375     def __reduce__(self, *args, **kwargs):  # real signature unknown
376         pass
377
378     def __repr__(self, *args, **kwargs):  # real signature unknown
379         """ Return repr(self). """
380         pass
381
382     tm_gmtoff = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
383     """offset from UTC in seconds"""  #以秒为单位偏移UTC
384
385     tm_hour = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
386     """hours, range [0, 23]"""
387
388     tm_isdst = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
389     """1 if summer time is in effect, 0 if not, and -1 if unknown"""
390
391     tm_mday = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
392     """day of month, range [1, 31]"""
393
394     tm_min = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
395     """minutes, range [0, 59]"""
396
397     tm_mon = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
398     """month of year, range [1, 12]"""
399
400     tm_sec = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
401     """seconds, range [0, 61])"""
402
403     tm_wday = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
404     """day of week, range [0, 6], Monday is 0"""
405
406     tm_yday = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
407     """day of year, range [1, 366]"""
408
409     tm_year = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
410     """year, for example, 1993"""
411
412     tm_zone = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
413     """abbreviation of timezone name""" #时区名称的缩写
414
415     n_fields = 11
416     n_sequence_fields = 9
417     n_unnamed_fields = 0
418
419
420 class __loader__(object):
421     """
422     Meta path import for built-in modules.
423     All methods are either class or static methods to avoid the need to
424     instantiate the class.
425     """
426     #元路径导入内置模块。所有方法都是类或静态方法,以避免需要实例化类。
427
428     @classmethod
429     def create_module(cls, *args, **kwargs):  # real signature unknown
430         """ Create a built-in module """
431         pass
432
433     @classmethod
434     def exec_module(cls, *args, **kwargs):  # real signature unknown
435         """ Exec a built-in module """
436         pass
437
438     @classmethod
439     def find_module(cls, *args, **kwargs):  # real signature unknown
440         """
441         Find the built-in module.
442         If 'path' is ever specified then the search is considered a failure.
443         This method is deprecated.  Use find_spec() instead.
444         """
445         #找到内置模块。如果指定了“path”,则认为搜索失败。这种方法不赞成使用。使用find_spec ()。
446         pass
447
448     @classmethod
449     def find_spec(cls, *args, **kwargs):  # real signature unknown
450         pass
451
452     @classmethod
453     def get_code(cls, *args, **kwargs):  # real signature unknown
454         """ Return None as built-in modules do not have code objects. """
455         #返回None,因为内置模块没有代码对象。
456         pass
457
458     @classmethod
459     def get_source(cls, *args, **kwargs):  # real signature unknown
460         """ Return None as built-in modules do not have source code. """
461         #没有返回作为内置模块没有源代码
462         pass
463
464     @classmethod
465     def is_package(cls, *args, **kwargs):  # real signature unknown
466         """ Return False as built-in modules are never packages. """
467         #返回False,因为内置模块从来不是包
468         pass
469
470     @classmethod
471     def load_module(cls, *args, **kwargs):  # real signature unknown
472         """
473         Load the specified module into sys.modules and return it.
474         This method is deprecated.  Use loader.exec_module instead.
475         """
476         #将指定的模块加载到sys中。模块并返回它。这种方法不赞成使用。使用加载程序。exec_module代替。
477         pass
478
479     def module_repr(module):  # reliably restored by inspect
480         """
481         Return repr for the module.
482         The method is deprecated.  The import machinery does the job itself.
483         """
484         #返回模块的repr。该方法不赞成使用。进口机器自己完成这项工作。
485         pass
486
487     def __init__(self, *args, **kwargs):  # real signature unknown
488         pass
489
490     __weakref__ = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
491     """list of weak references to the object (if defined)"""
492
493     __dict__ = None  # (!) real value is ''
494
495
496 # variables with complex values  具有复数的变量
497
498 tzname = (
499     'Öйú±ê׼ʱ¼ä',
500     'ÖйúÏÄÁîʱ',
501 )
502
503 __spec__ = None  # (!) real value is ''
time源代码.py
  • datetime模块:
'''datetime'''
#获取日期
import datetime
print(datetime.date)

#获取时分秒
import datetime
print(datetime.time)

#获取两者的整体
import datetime
print(datetime.datetime)

#获取当前的年月日时分秒
import datetime
print(datetime.datetime.now())

#获取向前或者向后某段时间的时间
import datetime
print(datetime.timedelta(-3))
print(datetime.timedelta(3))
print(datetime.datetime.now()+datetime.timedelta(hours=3))
print(datetime.datetime.now()+datetime.timedelta(minutes=3))
  • 随机模块random:
'''随机模块random'''
import  random

# 生成随机数,但必须做出相应转换
print(random.random())
print(int(random.random()*100))

# 生成整数随机数
print(random.randint(1,5))

# 生成顺序随机数
print(random.randrange(1,5))

# 随机生成序列中的某一项,可以是元组、列表、字符串
print(random.choice(["a","b","c","d"]))

# 随机生成字符串的两个数
print(random.sample("dgfdgfh",2))

# 随机生成浮点数
print(random.uniform(1,4))

# “洗牌”方法,将传入的序列重新打乱排序
l=[1,3,5,6,8]
random.shuffle(l)
print(l)
Python   模块-LMLPHPPython   模块-LMLPHP
  1 """Random variable generators.
  2
  3     integers
  4     --------
  5            uniform within range
  6
  7     sequences
  8     ---------
  9            pick random element
 10            pick random sample
 11            pick weighted random sample
 12            generate random permutation
 13
 14     distributions on the real line:
 15     ------------------------------
 16            uniform
 17            triangular
 18            normal (Gaussian)
 19            lognormal
 20            negative exponential
 21            gamma
 22            beta
 23            pareto
 24            Weibull
 25
 26     distributions on the circle (angles 0 to 2pi)
 27     ---------------------------------------------
 28            circular uniform
 29            von Mises
 30
 31 General notes on the underlying Mersenne Twister core generator:
 32
 33 * The period is 2**19937-1.
 34 * It is one of the most extensively tested generators in existence.
 35 * The random() method is implemented in C, executes in a single Python step,
 36   and is, therefore, threadsafe.
 37
 38 """
 39 '''随机变量发电机。
 40 整数
 41 - - - - - - - - - -
 42 统一的范围内
 43 序列
 44 - - - - - - - - - - - -
 45 选择随机元素
 46 选择随机样本
 47 随机抽样
 48 生成随机排列
 49 实线分布:
 50 -----------------------------
 51 统一的
 52 三角
 53 正常(高斯)
 54 对数正态
 55 负指数
 56 γ
 57 β
 58 帕累托
 59 威布尔
 60 圆上的分布(角度0到2)
 61 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 62 圆形的制服
 63 •冯•米塞斯
 64 关于潜在的Mersenne缠绕核心发生器的一般说明:
 65 *期间为2**1993 -1年。
 66 *它是现存最广泛测试的发电机之一。
 67 * random()方法在C语言中实现,在一个Python步骤中执行,
 68 因此,它是线程安全的。'''
 69
 70 from warnings import warn as _warn
 71 from types import MethodType as _MethodType, BuiltinMethodType as _BuiltinMethodType
 72 from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil
 73 from math import sqrt as _sqrt, acos as _acos, cos as _cos, sin as _sin
 74 from os import urandom as _urandom
 75 from _collections_abc import Set as _Set, Sequence as _Sequence
 76 from hashlib import sha512 as _sha512
 77 import itertools as _itertools
 78 import bisect as _bisect
 79 import os as _os
 80
 81 __all__ = ["Random","seed","random","uniform","randint","choice","sample",
 82            "randrange","shuffle","normalvariate","lognormvariate",
 83            "expovariate","vonmisesvariate","gammavariate","triangular",
 84            "gauss","betavariate","paretovariate","weibullvariate",
 85            "getstate","setstate", "getrandbits", "choices",
 86            "SystemRandom"]
 87
 88 NV_MAGICCONST = 4 * _exp(-0.5)/_sqrt(2.0)
 89 TWOPI = 2.0*_pi
 90 LOG4 = _log(4.0)
 91 SG_MAGICCONST = 1.0 + _log(4.5)
 92 BPF = 53        # Number of bits in a float
 93 RECIP_BPF = 2**-BPF
 94
 95
 96 # Translated by Guido van Rossum from C source provided by
 97 # Adrian Baddeley.  Adapted by Raymond Hettinger for use with
 98 # the Mersenne Twister  and os.urandom() core generators.
 99 #Guido van Rossum从C资料中搜索,Adrian Baddeley提供。由Raymond Hettinger改编,
100 # 用于Mersenne Twister和os.urandom()核心生成器。
101
102 import _random
103
104 class Random(_random.Random):
105     """Random number generator base class used by bound module functions.
106
107     Used to instantiate instances of Random to get generators that don't
108     share state.
109
110     Class Random can also be subclassed if you want to use a different basic
111     generator of your own devising: in that case, override the following
112     methods:  random(), seed(), getstate(), and setstate().
113     Optionally, implement a getrandbits() method so that randrange()
114     can cover arbitrarily large ranges.
115     """
116     #随机数生成器基类用于绑定模块函数。用于实例化随机实例以获得不共享状态的生成器。
117     # 如果您想使用自己设计的不同基本生成器,也可以对类Random进行子类化:在这种情况下,
118     # 重写以下方法:Random()、seed()、getstate()和setstate()。或者,
119     # 实现getrandbits()方法,使randrange()可以覆盖任意大的范围。
120
121     VERSION = 3     # used by getstate/setstate
122
123     def __init__(self, x=None):
124         """Initialize an instance.
125
126         Optional argument x controls seeding, as for Random.seed().
127         """
128         #初始化一个实例。可选参数x控制种子,如Random.seed()。
129
130         self.seed(x)
131         self.gauss_next = None
132
133     def seed(self, a=None, version=2):
134         """Initialize internal state from hashable object.
135
136         None or no argument seeds from current time or from an operating
137         system specific randomness source if available.
138
139         If *a* is an int, all bits are used.
140
141         For version 2 (the default), all of the bits are used if *a* is a str,
142         bytes, or bytearray.  For version 1 (provided for reproducing random
143         sequences from older versions of Python), the algorithm for str and
144         bytes generates a narrower range of seeds.
145         """
146         #从hashable对象初始化内部状态。没有或没有参数种子来自当前时间或从操作系统
147         # 特定随机性源(如果可用)。如果*a*是int,则使用所有位。对于版本2(默认),
148         # 如果*a*是str、字节或bytearray,则使用所有的位。对于版本1(用于从旧版本
149         # 的Python中复制随机序列),str和字节的算法生成的种子范围较窄。
150
151         if version == 1 and isinstance(a, (str, bytes)):
152             a = a.decode('latin-1') if isinstance(a, bytes) else a
153             x = ord(a[0]) << 7 if a else 0
154             for c in map(ord, a):
155                 x = ((1000003 * x) ^ c) & 0xFFFFFFFFFFFFFFFF
156             x ^= len(a)
157             a = -2 if x == -1 else x
158
159         if version == 2 and isinstance(a, (str, bytes, bytearray)):
160             if isinstance(a, str):
161                 a = a.encode()
162             a += _sha512(a).digest()
163             a = int.from_bytes(a, 'big')
164
165         super().seed(a)
166         self.gauss_next = None
167
168     def getstate(self):
169         """Return internal state; can be passed to setstate() later."""
170         #返回内部状态;可以稍后传递给setstate()。
171         return self.VERSION, super().getstate(), self.gauss_next
172
173     def setstate(self, state):
174         """Restore internal state from object returned by getstate()."""
175         #从getstate()返回的对象中恢复内部状态。
176         version = state[0]
177         if version == 3:
178             version, internalstate, self.gauss_next = state
179             super().setstate(internalstate)
180         elif version == 2:
181             version, internalstate, self.gauss_next = state
182             # In version 2, the state was saved as signed ints, which causes
183             #   inconsistencies between 32/64-bit systems. The state is
184             #   really unsigned 32-bit ints, so we convert negative ints from
185             #   version 2 to positive longs for version 3.
186             try:
187                 internalstate = tuple(x % (2**32) for x in internalstate)
188             except ValueError as e:
189                 raise TypeError from e
190             super().setstate(internalstate)
191         else:
192             raise ValueError("state with version %s passed to "
193                              "Random.setstate() of version %s" %
194                              (version, self.VERSION))
195
196 ## ---- Methods below this point do not need to be overridden when
197 ## ---- subclassing for the purpose of using a different core generator.
198
199 ## -------------------- pickle support  -------------------
200
201     # Issue 17489: Since __reduce__ was defined to fix #759889 this is no
202     # longer called; we leave it here because it has been here since random was
203     # rewritten back in 2001 and why risk breaking something.
204     def __getstate__(self): # for pickle
205         return self.getstate()
206
207     def __setstate__(self, state):  # for pickle
208         self.setstate(state)
209
210     def __reduce__(self):
211         return self.__class__, (), self.getstate()
212
213 ## -------------------- integer methods  -------------------
214
215     def randrange(self, start, stop=None, step=1, _int=int):
216         """Choose a random item from range(start, stop[, step]).
217
218         This fixes the problem with randint() which includes the
219         endpoint; in Python this is usually not what you want.
220         """
221         #从范围(开始,停止[,步骤])中随机选择一个项目。这修复了randint()中包含
222         # 端点的问题;在Python中,这通常不是您想要的。
223
224         # This code is a bit messy to make it fast for the
225         # common case while still doing adequate error checking.
226         istart = _int(start)
227         if istart != start:
228             raise ValueError("non-integer arg 1 for randrange()")
229         if stop is None:
230             if istart > 0:
231                 return self._randbelow(istart)
232             raise ValueError("empty range for randrange()")
233
234         # stop argument supplied.
235         istop = _int(stop)
236         if istop != stop:
237             raise ValueError("non-integer stop for randrange()")
238         width = istop - istart
239         if step == 1 and width > 0:
240             return istart + self._randbelow(width)
241         if step == 1:
242             raise ValueError("empty range for randrange() (%d,%d, %d)" % (istart, istop, width))
243
244         # Non-unit step argument supplied.  #提供了非单位步骤参数。
245         istep = _int(step)
246         if istep != step:
247             raise ValueError("non-integer step for randrange()")
248         if istep > 0:
249             n = (width + istep - 1) // istep
250         elif istep < 0:
251             n = (width + istep + 1) // istep
252         else:
253             raise ValueError("zero step for randrange()")
254
255         if n <= 0:
256             raise ValueError("empty range for randrange()")
257
258         return istart + istep*self._randbelow(n)
259
260     def randint(self, a, b):
261         """Return random integer in range [a, b], including both end points.
262         """
263         #返回范围[a, b]中的随机整数,包括两个端点。
264
265         return self.randrange(a, b+1)
266
267     def _randbelow(self, n, int=int, maxsize=1<<BPF, type=type,
268                    Method=_MethodType, BuiltinMethod=_BuiltinMethodType):
269         "Return a random int in the range [0,n).  Raises ValueError if n==0."
270         #在范围[0,n]中返回一个随机整数。如果n= 0,将引发ValueError。
271
272         random = self.random
273         getrandbits = self.getrandbits
274         # Only call self.getrandbits if the original random() builtin method
275         # has not been overridden or if a new getrandbits() was supplied.
276         #只叫自我。如果未覆盖原来的random()内建方法,或者提供了新的getrandbits(),则为getrandbits()。
277         if type(random) is BuiltinMethod or type(getrandbits) is Method:
278             k = n.bit_length()  # don't use (n-1) here because n can be 1
279             r = getrandbits(k)          # 0 <= r < 2**k
280             while r >= n:
281                 r = getrandbits(k)
282             return r
283         # There's an overridden random() method but no new getrandbits() method,
284         # so we can only use random() from here.
285         #有一个被重写的random()方法,但是没有新的getrandbits()方法,所以我们只能从这里使用random()。
286         if n >= maxsize:
287             _warn("Underlying random() generator does not supply \n"
288                 "enough bits to choose from a population range this large.\n"
289                 "To remove the range limitation, add a getrandbits() method.")
290             #基础random()生成器没有提供足够的位从这么大的总体范围中进行选择。
291             # 要消除范围限制,添加一个getrandbits()方法.
292             return int(random() * n)
293         if n == 0:
294             raise ValueError("Boundary cannot be zero边界不能为零")
295         rem = maxsize % n
296         limit = (maxsize - rem) / maxsize   # int(limit * maxsize) % n == 0
297         r = random()
298         while r >= limit:
299             r = random()
300         return int(r*maxsize) % n
301
302 ## -------------------- sequence methods  -------------------
303
304     def choice(self, seq):
305         """Choose a random element from a non-empty sequence."""
306         #从非空序列中选择一个随机元素。
307         try:
308             i = self._randbelow(len(seq))
309         except ValueError:
310             raise IndexError('Cannot choose from an empty sequence') from None
311         return seq[i]
312
313     def shuffle(self, x, random=None):
314         """Shuffle list x in place, and return None.
315
316         Optional argument random is a 0-argument function returning a
317         random float in [0.0, 1.0); if it is the default None, the
318         standard random.random will be used.
319         """
320         #将Shuffle列表x放在适当的位置,并返回None。可选参数random是一个0参数函数,
321         # 返回[0.0,1.0]中的一个随机浮点数;如果是默认的None,则为标准随机。将使用random。
322
323         if random is None:
324             randbelow = self._randbelow
325             for i in reversed(range(1, len(x))):
326                 # pick an element in x[:i+1] with which to exchange x[i]
327                 j = randbelow(i+1)
328                 x[i], x[j] = x[j], x[i]
329         else:
330             _int = int
331             for i in reversed(range(1, len(x))):
332                 # pick an element in x[:i+1] with which to exchange x[i]
333                 j = _int(random() * (i+1))
334                 x[i], x[j] = x[j], x[i]
335
336     def sample(self, population, k):
337         """Chooses k unique random elements from a population sequence or set.
338
339         Returns a new list containing elements from the population while
340         leaving the original population unchanged.  The resulting list is
341         in selection order so that all sub-slices will also be valid random
342         samples.  This allows raffle winners (the sample) to be partitioned
343         into grand prize and second place winners (the subslices).
344
345         Members of the population need not be hashable or unique.  If the
346         population contains repeats, then each occurrence is a possible
347         selection in the sample.
348
349         To choose a sample in a range of integers, use range as an argument.
350         This is especially fast and space efficient for sampling from a
351         large population:   sample(range(10000000), 60)
352         """
353         #从一个总体序列或集合中选择k个唯一的随机元素。结果列表是按选择顺序排列的,
354         # 因此所有的子切片也将是有效的随机样本。这允许抽奖获奖者(样本)被划分为大奖
355         # 和第二名获奖者(子部分)。人口中的成员不需要是有用的或独特的。如果总体包含
356         # 重复,那么每个事件都是样本中可能的选择。要在整数范围内选择一个样本,使用
357         # range作为参数。这对于从大量人群中进行抽样来说特别快速和节省空间:样本
358         # (范围(10000000),60)
359
360         # Sampling without replacement entails tracking either potential
361         # selections (the pool) in a list or previous selections in a set.
362         ##不进行替换的抽样需要跟踪列表中的潜在选择(池)或集合中的先前选择。
363
364         # When the number of selections is small compared to the
365         # population, then tracking selections is efficient, requiring
366         # only a small set and an occasional reselection.  For
367         # a larger number of selections, the pool tracking method is
368         # preferred since the list takes less space than the
369         # set and it doesn't suffer from frequent reselections.
370         #当选择的数量与总体数量相比很小时,跟踪选择是有效的,只需要一个小的集合和偶尔的重新选择。对于更多的选择,最好使用池跟踪方法,因为列表比集合占用的空间更少,而且不会频繁地重新选择。
371
372         if isinstance(population, _Set):
373             population = tuple(population)
374         if not isinstance(population, _Sequence):
375             raise TypeError("Population must be a sequence or set.  For dicts, use list(d).")
376         randbelow = self._randbelow
377         n = len(population)
378         if not 0 <= k <= n:
379             raise ValueError("Sample larger than population or is negative")
380         result = [None] * k
381         setsize = 21        # size of a small set minus size of an empty list 一个小集合的大小减去一个空列表的大小
382         if k > 5:
383             setsize += 4 ** _ceil(_log(k * 3, 4)) # table size for big sets
384         if n <= setsize:
385             # An n-length list is smaller than a k-length set
386             pool = list(population)
387             for i in range(k):         # invariant:  non-selected at [0,n-i)
388                 j = randbelow(n-i)
389                 result[i] = pool[j]
390                 pool[j] = pool[n-i-1]   # move non-selected item into vacancy
391         else:
392             selected = set()
393             selected_add = selected.add
394             for i in range(k):
395                 j = randbelow(n)
396                 while j in selected:
397                     j = randbelow(n)
398                 selected_add(j)
399                 result[i] = population[j]
400         return result
401
402     def choices(self, population, weights=None, *, cum_weights=None, k=1):
403         """Return a k sized list of population elements chosen with replacement.
404         If the relative weights or cumulative weights are not specified,
405         the selections are made with equal probability.
406         """
407         #返回替换后选择的k大小的总体元素列表。如果没有指定相对权重或累积权重,则选择的概率是相等的。
408         random = self.random
409         if cum_weights is None:
410             if weights is None:
411                 _int = int
412                 total = len(population)
413                 return [population[_int(random() * total)] for i in range(k)]
414             cum_weights = list(_itertools.accumulate(weights))
415         elif weights is not None:
416             raise TypeError('Cannot specify both weights and cumulative weights')
417         if len(cum_weights) != len(population):
418             raise ValueError('The number of weights does not match the population')
419         bisect = _bisect.bisect
420         total = cum_weights[-1]
421         return [population[bisect(cum_weights, random() * total)] for i in range(k)]
422
423 ## -------------------- real-valued distributions  -------------------
424
425 ## -------------------- uniform distribution -------------------
426
427     def uniform(self, a, b):
428         "Get a random number in the range [a, b) or [a, b] depending on rounding."
429         #根据四舍五入,在[a, b]或[a, b]范围内得到一个随机数。
430         return a + (b-a) * self.random()
431
432 ## -------------------- triangular --------------------
433
434     def triangular(self, low=0.0, high=1.0, mode=None):
435         """Triangular distribution.
436
437         Continuous distribution bounded by given lower and upper limits,
438         and having a given mode value in-between.
439
440         http://en.wikipedia.org/wiki/Triangular_distribution
441         """
442         #由给定的上限值和下限值所限定的连续分布,并且在两者之间具有给定的模态值。
443         u = self.random()
444         try:
445             c = 0.5 if mode is None else (mode - low) / (high - low)
446         except ZeroDivisionError:
447             return low
448         if u > c:
449             u = 1.0 - u
450             c = 1.0 - c
451             low, high = high, low
452         return low + (high - low) * _sqrt(u * c)
453
454 ## -------------------- normal distribution --------------------
455
456     def normalvariate(self, mu, sigma):
457         """Normal distribution.
458
459         mu is the mean, and sigma is the standard deviation.
460         """
461         #mu是均值,是标准差。
462         # mu = mean, sigma = standard deviation
463
464         # Uses Kinderman and Monahan method. Reference: Kinderman,
465         # A.J. and Monahan, J.F., "Computer generation of random
466         # variables using the ratio of uniform deviates", ACM Trans
467         # Math Software, 3, (1977), pp257-260.
468
469         random = self.random
470         while 1:
471             u1 = random()
472             u2 = 1.0 - random()
473             z = NV_MAGICCONST*(u1-0.5)/u2
474             zz = z*z/4.0
475             if zz <= -_log(u2):
476                 break
477         return mu + z*sigma
478
479 ## -------------------- lognormal distribution --------------------
480
481     def lognormvariate(self, mu, sigma):
482         """Log normal distribution.
483
484         If you take the natural logarithm of this distribution, you'll get a
485         normal distribution with mean mu and standard deviation sigma.
486         mu can have any value, and sigma must be greater than zero.
487         """
488         #如果对这个分布取自然对数,就会得到均值和标准差的正态分布。可以有任何值,必须大于零。
489         return _exp(self.normalvariate(mu, sigma))
490
491 ## -------------------- exponential distribution --------------------
492
493     def expovariate(self, lambd):
494         """Exponential distribution.
495
496         lambd is 1.0 divided by the desired mean.  It should be
497         nonzero.  (The parameter would be called "lambda", but that is
498         a reserved word in Python.)  Returned values range from 0 to
499         positive infinity if lambd is positive, and from negative
500         infinity to 0 if lambd is negative.
501         """
502         #指数分布。lambd等于1。0除以期望的平均值。它应该是非零的。(该参数将被称为
503         # “lambda”,但这在Python中是一个保留字。)返回的值范围从0到正无穷,如果lambd
504         # 为正,从负无穷到0如果lambd为负。
505
506         # lambd: rate lambd = 1/mean
507         # ('lambda' is a Python reserved word)
508
509         # we use 1-random() instead of random() to preclude the
510         # possibility of taking the log of zero.
511         #我们使用1-random()而不是random()来排除取log(0)的可能性。
512         return -_log(1.0 - self.random())/lambd
513
514 ## -------------------- von Mises distribution --------------------
515
516     def vonmisesvariate(self, mu, kappa):
517         """Circular data distribution.
518
519         mu is the mean angle, expressed in radians between 0 and 2*pi, and
520         kappa is the concentration parameter, which must be greater than or
521         equal to zero.  If kappa is equal to zero, this distribution reduces
522         to a uniform random angle over the range 0 to 2*pi.
523         """
524         #循环数据分布。mu是平均角度,以弧度表示在0到2*之间,kappa是浓度参数,必须
525         # 大于等于0。如果kappa等于0,这个分布会在0到2*之间减小为均匀的随机角度。
526
527         # mu:    mean angle (in radians between 0 and 2*pi)
528         # mu: 平均角度(弧度在0到2*之间)
529         # kappa: concentration parameter kappa (>= 0)
530         # if kappa = 0 generate uniform random angle
531         #kappa:当kappa = 0时,浓度参数kappa(>= 0)产生均匀随机角
532
533         # Based upon an algorithm published in: Fisher, N.I.,
534         # "Statistical Analysis of Circular Data", Cambridge
535         # University Press, 1993.
536         # 基于Fisher, N.I.的一种算法《循环数据的统计分析》,剑桥大学出版社,1993年。
537
538         # Thanks to Magnus Kessler for a correction to the
539         # implementation of step 4.
540         #感谢Magnus Kessler更正第4步的实现。
541
542         random = self.random
543         if kappa <= 1e-6:
544             return TWOPI * random()
545
546         s = 0.5 / kappa
547         r = s + _sqrt(1.0 + s * s)
548
549         while 1:
550             u1 = random()
551             z = _cos(_pi * u1)
552
553             d = z / (r + z)
554             u2 = random()
555             if u2 < 1.0 - d * d or u2 <= (1.0 - d) * _exp(d):
556                 break
557
558         q = 1.0 / r
559         f = (q + z) / (1.0 + q * z)
560         u3 = random()
561         if u3 > 0.5:
562             theta = (mu + _acos(f)) % TWOPI
563         else:
564             theta = (mu - _acos(f)) % TWOPI
565
566         return theta
567
568 ## -------------------- gamma distribution --------------------
569
570     def gammavariate(self, alpha, beta):
571         """Gamma distribution.  Not the gamma function!
572
573         Conditions on the parameters are alpha > 0 and beta > 0.
574         The probability distribution function is:
575         #伽马分布。不是函数!参数的条件是> 0和> 0。概率分布函数为:
576
577                     x ** (alpha - 1) * math.exp(-x / beta)
578           pdf(x) =  --------------------------------------
579                       math.gamma(alpha) * beta ** alpha
580
581         """
582
583         # alpha > 0, beta > 0, mean is alpha*beta, variance is alpha*beta**2
584
585         # Warning: a few older sources define the gamma distribution in terms
586         # of alpha > -1.0
587         if alpha <= 0.0 or beta <= 0.0:
588             raise ValueError('gammavariate: alpha and beta must be > 0.0')
589
590         random = self.random
591         if alpha > 1.0:
592
593             # Uses R.C.H. Cheng, "The generation of Gamma
594             # variables with non-integral shape parameters",
595             # Applied Statistics, (1977), 26, No. 1, p71-74
596
597             ainv = _sqrt(2.0 * alpha - 1.0)
598             bbb = alpha - LOG4
599             ccc = alpha + ainv
600
601             while 1:
602                 u1 = random()
603                 if not 1e-7 < u1 < .9999999:
604                     continue
605                 u2 = 1.0 - random()
606                 v = _log(u1/(1.0-u1))/ainv
607                 x = alpha*_exp(v)
608                 z = u1*u1*u2
609                 r = bbb+ccc*v-x
610                 if r + SG_MAGICCONST - 4.5*z >= 0.0 or r >= _log(z):
611                     return x * beta
612
613         elif alpha == 1.0:
614             # expovariate(1/beta)
615             u = random()
616             while u <= 1e-7:
617                 u = random()
618             return -_log(u) * beta
619
620         else:   # alpha is between 0 and 1 (exclusive)
621
622             # Uses ALGORITHM GS of Statistical Computing - Kennedy & Gentle
623             #alpha在0到1之间(独家)   #使用统计计算的算法GS - Kennedy & Gentle
624
625             while 1:
626                 u = random()
627                 b = (_e + alpha)/_e
628                 p = b*u
629                 if p <= 1.0:
630                     x = p ** (1.0/alpha)
631                 else:
632                     x = -_log((b-p)/alpha)
633                 u1 = random()
634                 if p > 1.0:
635                     if u1 <= x ** (alpha - 1.0):
636                         break
637                 elif u1 <= _exp(-x):
638                     break
639             return x * beta
640
641 ## -------------------- Gauss (faster alternative) --------------------
642
643     def gauss(self, mu, sigma):
644         """Gaussian distribution.
645
646         mu is the mean, and sigma is the standard deviation.  This is
647         slightly faster than the normalvariate() function.
648         Not thread-safe without a lock around calls.
649         """
650         #高斯分布。是均值,是标准差。这比normalvariate()函数稍微快一些。没有锁的调用不是线程安全的。
651
652         # When x and y are two variables from [0, 1), uniformly
653         # distributed, then
654         #
655         #    cos(2*pi*x)*sqrt(-2*log(1-y))
656         #    sin(2*pi*x)*sqrt(-2*log(1-y))
657         #
658         # are two *independent* variables with normal distribution
659         # 两个独立的变量是否具有正态分布
660         # (mu = 0, sigma = 1).
661         # (Lambert Meertens)
662         # (corrected version; bug discovered by Mike Miller, fixed by LM)
663         #(修正版;Mike Miller发现的bug, LM修复
664
665         # Multithreading note: When two threads call this function
666         # simultaneously, it is possible that they will receive the
667         # same return value.  The window is very small though.  To
668         # avoid this, you have to use a lock around all calls.  (I
669         # didn't want to slow this down in the serial case by using a
670         # lock here.)
671         #注意:当两个线程同时调用这个函数时,它们可能会收到相同的返回值。窗户很小。
672         # 为了避免这种情况,您必须在所有调用周围使用锁。(我不想在串行情况下使用锁
673         # 来减慢速度。)
674
675         random = self.random
676         z = self.gauss_next
677         self.gauss_next = None
678         if z is None:
679             x2pi = random() * TWOPI
680             g2rad = _sqrt(-2.0 * _log(1.0 - random()))
681             z = _cos(x2pi) * g2rad
682             self.gauss_next = _sin(x2pi) * g2rad
683
684         return mu + z*sigma
685
686 ## -------------------- beta --------------------
687 ## See
688 ## http://mail.python.org/pipermail/python-bugs-list/2001-January/003752.html
689 ## for Ivan Frohne's insightful analysis of why the original implementation:
690 ##
691 ##    def betavariate(self, alpha, beta):
692 ##        # Discrete Event Simulation in C, pp 87-88.
693 ##
694 ##        y = self.expovariate(alpha)
695 ##        z = self.expovariate(1.0/beta)
696 ##        return z/(y+z)
697 ##
698 ## was dead wrong, and how it probably got that way.
699
700     def betavariate(self, alpha, beta):
701         """Beta distribution.
702
703         Conditions on the parameters are alpha > 0 and beta > 0.
704         Returned values range between 0 and 1.
705         """
706         #贝塔分布。参数的条件是> 0和> 0。返回的值范围在0到1之间。
707
708         # This version due to Janne Sinkkonen, and matches all the std
709         # texts (e.g., Knuth Vol 2 Ed 3 pg 134 "the beta distribution").
710         #这个版本由于Janne Sinkkonen,并且匹配所有的std文本(例如,Knuth Vol 2 Ed 3 pg 134“beta发行版”)。
711         y = self.gammavariate(alpha, 1.0)
712         if y == 0:
713             return 0.0
714         else:
715             return y / (y + self.gammavariate(beta, 1.0))
716
717 ## -------------------- Pareto --------------------
718
719     def paretovariate(self, alpha):
720         """Pareto distribution.  alpha is the shape parameter."""
721         #帕累托分布。是形状参数。
722         # Jain, pg. 495
723
724         u = 1.0 - self.random()
725         return 1.0 / u ** (1.0/alpha)
726
727 ## -------------------- Weibull --------------------
728
729     def weibullvariate(self, alpha, beta):
730         """Weibull distribution.
731
732         alpha is the scale parameter and beta is the shape parameter.
733         """
734         #威布尔分布。是尺度参数,是形状参数。
735         # Jain, pg. 499; bug fix courtesy Bill Arms
736
737         u = 1.0 - self.random()
738         return alpha * (-_log(u)) ** (1.0/beta)
739
740 ## --------------- Operating System Random Source  ------------------
741
742 class SystemRandom(Random):
743     """Alternate random number generator using sources provided
744     by the operating system (such as /dev/urandom on Unix or
745     CryptGenRandom on Windows).
746      Not available on all systems (see os.urandom() for details).
747     """
748     #使用操作系统提供的源(例如Unix上的/dev/urandom或Windows上的CryptGenRandom)
749     # 替换随机数生成器。不能在所有系统上使用(详见os.urandom())。
750
751     def random(self):
752         """Get the next random number in the range [0.0, 1.0)."""
753         #获取范围内的下一个随机数[0.0,1.0]。
754         return (int.from_bytes(_urandom(7), 'big') >> 3) * RECIP_BPF
755
756     def getrandbits(self, k):
757         """getrandbits(k) -> x.  Generates an int with k random bits."""
758         #getrandbits(k) -> x.用k个随机位生成一个int。
759         if k <= 0:
760             raise ValueError('number of bits must be greater than zero')
761         if k != int(k):
762             raise TypeError('number of bits should be an integer')
763         numbytes = (k + 7) // 8                       # bits / 8 and rounded up
764         x = int.from_bytes(_urandom(numbytes), 'big')
765         return x >> (numbytes * 8 - k)                # trim excess bits
766
767     def seed(self, *args, **kwds):
768         "Stub method.  Not used for a system random number generator."
769         #存根方法。不用于系统随机数生成器。
770         return None
771
772     def _notimplemented(self, *args, **kwds):
773         "Method should not be called for a system random number generator."
774         #方法不应用于系统随机数生成器。
775         raise NotImplementedError('System entropy source does not have state.')
776     getstate = setstate = _notimplemented
777
778 ## -------------------- test program --------------------
779
780 def _test_generator(n, func, args):
781     import time
782     print(n, 'times', func.__name__)
783     total = 0.0
784     sqsum = 0.0
785     smallest = 1e10
786     largest = -1e10
787     t0 = time.time()
788     for i in range(n):
789         x = func(*args)
790         total += x
791         sqsum = sqsum + x*x
792         smallest = min(x, smallest)
793         largest = max(x, largest)
794     t1 = time.time()
795     print(round(t1-t0, 3), 'sec,', end=' ')
796     avg = total/n
797     stddev = _sqrt(sqsum/n - avg*avg)
798     print('avg %g, stddev %g, min %g, max %g\n' % \
799               (avg, stddev, smallest, largest))
800
801
802 def _test(N=2000):
803     _test_generator(N, random, ())
804     _test_generator(N, normalvariate, (0.0, 1.0))
805     _test_generator(N, lognormvariate, (0.0, 1.0))
806     _test_generator(N, vonmisesvariate, (0.0, 1.0))
807     _test_generator(N, gammavariate, (0.01, 1.0))
808     _test_generator(N, gammavariate, (0.1, 1.0))
809     _test_generator(N, gammavariate, (0.1, 2.0))
810     _test_generator(N, gammavariate, (0.5, 1.0))
811     _test_generator(N, gammavariate, (0.9, 1.0))
812     _test_generator(N, gammavariate, (1.0, 1.0))
813     _test_generator(N, gammavariate, (2.0, 1.0))
814     _test_generator(N, gammavariate, (20.0, 1.0))
815     _test_generator(N, gammavariate, (200.0, 1.0))
816     _test_generator(N, gauss, (0.0, 1.0))
817     _test_generator(N, betavariate, (3.0, 3.0))
818     _test_generator(N, triangular, (0.0, 1.0, 1.0/3.0))
819
820 # Create one instance, seeded from current time, and export its methods
821 # as module-level functions.  The functions share state across all uses
822 #(both in the user's code and in the Python libraries), but that's fine
823 # for most programs and is easier for the casual user than making them
824 # instantiate their own Random() instance.
825 #创建一个实例,从当前时间播种,并将其方法导出为模块级函数。这些函数在所有的使用中都
826 # 共享状态(在用户的代码和Python库中都是如此),但是对于大多数程序来说这没什么问题,
827 # 而且对于普通用户来说比让它们实例化自己的Random()实例更容易。
828
829 _inst = Random()
830 seed = _inst.seed
831 random = _inst.random
832 uniform = _inst.uniform
833 triangular = _inst.triangular
834 randint = _inst.randint
835 choice = _inst.choice
836 randrange = _inst.randrange
837 sample = _inst.sample
838 shuffle = _inst.shuffle
839 choices = _inst.choices
840 normalvariate = _inst.normalvariate
841 lognormvariate = _inst.lognormvariate
842 expovariate = _inst.expovariate
843 vonmisesvariate = _inst.vonmisesvariate
844 gammavariate = _inst.gammavariate
845 gauss = _inst.gauss
846 betavariate = _inst.betavariate
847 paretovariate = _inst.paretovariate
848 weibullvariate = _inst.weibullvariate
849 getstate = _inst.getstate
850 setstate = _inst.setstate
851 getrandbits = _inst.getrandbits
852
853 if hasattr(_os, "fork"):
854     _os.register_at_fork(after_in_child=_inst.seed)
855
856
857 if __name__ == '__main__':
858     _test()
random源代码.py

random模块可用来模拟用户登录的随机验证:

Python   模块-LMLPHPPython   模块-LMLPHP
import random
Flag=1
i=1
while Flag:
    s = int(random.random() * 10)
    if i<4:
        list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
        c = ['l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u']
        b = [s, 2*s, c[s], list[s]]
        random.shuffle(b)
        a = '%s%s%s%s' % (b[0], b[1], b[2], b[3])
        print(a)
        n=input('请输入验证码:\n')

        if n==a:
            print('验证成功')
            Flag=0
        else:
            print('验证失败')
            i+=1
    else:
        print('三次验证失败,请重新登录')
        break
随机验证
  • os模块:
'''os'''
#获取本程序当前的操作目录
import os
print(os.getcwd())

#切换当前目录
import os
os.chdir(r"c:")  #r是用来区分反斜杠,使其有意义
print(os.getcwd())

#返回当前目录(.一点表示当前, ..两点表示返回上级目录)
# (在cmd中使用cd.  cd..用于返回目录)
import os
print(os.curdir)  #当前
print(os.pardir)  #上级

#创建递归目录(多级)
import os
os.makedirs(r'c:/b/c')

#递归删除,直到删除某一项不为空为止
import os
os.removedirs(r'c:/a/b/c')

#逐个创建文件
import os
os.mkdir(r'c:\a\c')

#逐个删除
import os
os.rmdir(r'c:\a\c')

#显示指定目录下所有的程序
import os
print(os.listdir("."))  #本目录
print(os.listdir("..")) #上级目录

#删除本目录的文件
import os
os.remove("file.txt")

#修改名字
import os
os.rename(r'',r'')

#显示该文件的目录信息,即创建时间
print(os.stat(r""))

#路径分割符
print(os.sep)  #win--\,\\   linux--/

print(os.linesep)

#用分号;表示字符串的分割
print(os.pathsep)

#显示环境变量
print(os.environ)

#nt表示win7系统
print(os.name)  #linux:posix

#显示系统命令,将字符串以乱码形式显示
os.system("dir")

#返回文件绝对路径
print(os.path.dirname(__file__))

#判断是否是一个文件
print(os.path.isfile())

#判断是否是绝对路径
os.path.isabs()

os.path.isdir()

#用于组合路径的方法
print(os.path.join(r''))

#返回文件最后存储时间
print(os.path.getatime("sys源代码.py"))
Python   模块-LMLPHPPython   模块-LMLPHP
   1 r"""OS routines for NT or Posix depending on what system we're on.
   2 #NT或Posix的操作系统例程取决于我们所使用的系统。
   3 This exports:
   4   - all functions from posix or nt, e.g. unlink, stat, etc.
   5     #posix或nt的所有功能,例如unlink、stat等。
   6   - os.path is either posixpath or ntpath
   7     #操作系统。路径是posixpath或ntpath
   8   - os.name is either 'posix' or 'nt'
   9     #os.name要么是posix,要么是nt
  10   - os.curdir is a string representing the current directory (always '.')
  11     #os.curdir是一个字符串,表示当前目录(总是'.')。
  12   - os.pardir is a string representing the parent directory (always '..')
  13     #os.pardir是一个字符串,表示父目录(总是'..')
  14   - os.sep is the (or a most common) pathname separator ('/' or '\\')
  15     #os.sep是(或最常见的)路径名分隔符('/'或'\\')
  16   - os.extsep is the extension separator (always '.')
  17     #os.extsep是扩展分隔符(总是'.')。
  18   - os.altsep is the alternate pathname separator (None or '/')
  19     #os.altsep是替代路径名分隔符(None或'/')
  20   - os.pathsep is the component separator used in $PATH etc
  21     #os.pathsep是用于$PATH等的组件分隔符
  22   - os.linesep is the line separator in text files ('\r' or '\n' or '\r\n')
  23     #os.linesep是文本文件中的行分隔符('\r'或'\n'或'\r\n')
  24   - os.defpath is the default search path for executables
  25     #os.defpath是可执行文件的默认搜索路径
  26   - os.devnull is the file path of the null device ('/dev/null', etc.)
  27     #os.devnull是空设备('/dev/null'等)的文件路径
  28 Programs that import and use 'os' stand a better chance of being
  29 portable between different platforms.  Of course, they must then
  30 only use functions that are defined by all platforms (e.g., unlink
  31 and opendir), and leave all pathname manipulation to os.path
  32 (e.g., split and join).
  33 #导入和使用“os”的程序更有可能存在在不同平台之间可移植。当然,他们必须这样做只使用
  34 所有平台定义的函数(例如,unlink),并将所有路径名操作留给操作系统.path(例如,分开并加入)。
  35 """
  36
  37 #'
  38 import abc
  39 import sys
  40 import stat as st
  41
  42 _names = sys.builtin_module_names
  43
  44 # Note:  more names are added to __all__ later.
  45 __all__ = ["altsep", "curdir", "pardir", "sep", "pathsep", "linesep",
  46            "defpath", "name", "path", "devnull", "SEEK_SET", "SEEK_CUR",
  47            "SEEK_END", "fsencode", "fsdecode", "get_exec_path", "fdopen",
  48            "popen", "extsep"]
  49
  50 def _exists(name):
  51     return name in globals()
  52
  53 def _get_exports_list(module):
  54     try:
  55         return list(module.__all__)
  56     except AttributeError:
  57         return [n for n in dir(module) if n[0] != '_']
  58
  59 # Any new dependencies of the os module and/or changes in path separator
  60 # requires updating importlib as well.
  61 if 'posix' in _names:
  62     name = 'posix'
  63     linesep = '\n'
  64     from posix import *
  65     try:
  66         from posix import _exit
  67         __all__.append('_exit')
  68     except ImportError:
  69         pass
  70     import posixpath as path
  71
  72     try:
  73         from posix import _have_functions
  74     except ImportError:
  75         pass
  76
  77     import posix
  78     __all__.extend(_get_exports_list(posix))
  79     del posix
  80
  81 elif 'nt' in _names:
  82     name = 'nt'
  83     linesep = '\r\n'
  84     from nt import *
  85     try:
  86         from nt import _exit
  87         __all__.append('_exit')
  88     except ImportError:
  89         pass
  90     import ntpath as path
  91
  92     import nt
  93     __all__.extend(_get_exports_list(nt))
  94     del nt
  95
  96     try:
  97         from nt import _have_functions
  98     except ImportError:
  99         pass
 100
 101 else:
 102     raise ImportError('no os specific module found')
 103
 104 sys.modules['os.path'] = path
 105 from os.path import (curdir, pardir, sep, pathsep, defpath, extsep, altsep,
 106     devnull)
 107
 108 del _names
 109
 110
 111 if _exists("_have_functions"):
 112     _globals = globals()
 113     def _add(str, fn):
 114         if (fn in _globals) and (str in _have_functions):
 115             _set.add(_globals[fn])
 116
 117     _set = set()
 118     _add("HAVE_FACCESSAT",  "access")
 119     _add("HAVE_FCHMODAT",   "chmod")
 120     _add("HAVE_FCHOWNAT",   "chown")
 121     _add("HAVE_FSTATAT",    "stat")
 122     _add("HAVE_FUTIMESAT",  "utime")
 123     _add("HAVE_LINKAT",     "link")
 124     _add("HAVE_MKDIRAT",    "mkdir")
 125     _add("HAVE_MKFIFOAT",   "mkfifo")
 126     _add("HAVE_MKNODAT",    "mknod")
 127     _add("HAVE_OPENAT",     "open")
 128     _add("HAVE_READLINKAT", "readlink")
 129     _add("HAVE_RENAMEAT",   "rename")
 130     _add("HAVE_SYMLINKAT",  "symlink")
 131     _add("HAVE_UNLINKAT",   "unlink")
 132     _add("HAVE_UNLINKAT",   "rmdir")
 133     _add("HAVE_UTIMENSAT",  "utime")
 134     supports_dir_fd = _set
 135
 136     _set = set()
 137     _add("HAVE_FACCESSAT",  "access")
 138     supports_effective_ids = _set
 139
 140     _set = set()
 141     _add("HAVE_FCHDIR",     "chdir")
 142     _add("HAVE_FCHMOD",     "chmod")
 143     _add("HAVE_FCHOWN",     "chown")
 144     _add("HAVE_FDOPENDIR",  "listdir")
 145     _add("HAVE_FDOPENDIR",  "scandir")
 146     _add("HAVE_FEXECVE",    "execve")
 147     _set.add(stat) # fstat always works
 148     _add("HAVE_FTRUNCATE",  "truncate")
 149     _add("HAVE_FUTIMENS",   "utime")
 150     _add("HAVE_FUTIMES",    "utime")
 151     _add("HAVE_FPATHCONF",  "pathconf")
 152     if _exists("statvfs") and _exists("fstatvfs"): # mac os x10.3
 153         _add("HAVE_FSTATVFS", "statvfs")
 154     supports_fd = _set
 155
 156     _set = set()
 157     _add("HAVE_FACCESSAT",  "access")
 158     # Some platforms don't support lchmod().  Often the function exists
 159     # anyway, as a stub that always returns ENOSUP or perhaps EOPNOTSUPP.
 160     # (No, I don't know why that's a good design.)  ./configure will detect
 161     # this and reject it--so HAVE_LCHMOD still won't be defined on such
 162     # platforms.  This is Very Helpful.
 163     #
 164     # However, sometimes platforms without a working lchmod() *do* have
 165     # fchmodat().  (Examples: Linux kernel 3.2 with glibc 2.15,
 166     # OpenIndiana 3.x.)  And fchmodat() has a flag that theoretically makes
 167     # it behave like lchmod().  So in theory it would be a suitable
 168     # replacement for lchmod().  But when lchmod() doesn't work, fchmodat()'s
 169     # flag doesn't work *either*.  Sadly ./configure isn't sophisticated
 170     # enough to detect this condition--it only determines whether or not
 171     # fchmodat() minimally works.
 172     #
 173     # Therefore we simply ignore fchmodat() when deciding whether or not
 174     # os.chmod supports follow_symlinks.  Just checking lchmod() is
 175     # sufficient.  After all--if you have a working fchmodat(), your
 176     # lchmod() almost certainly works too.
 177     #
 178     # _add("HAVE_FCHMODAT",   "chmod")
 179     _add("HAVE_FCHOWNAT",   "chown")
 180     _add("HAVE_FSTATAT",    "stat")
 181     _add("HAVE_LCHFLAGS",   "chflags")
 182     _add("HAVE_LCHMOD",     "chmod")
 183     if _exists("lchown"): # mac os x10.3
 184         _add("HAVE_LCHOWN", "chown")
 185     _add("HAVE_LINKAT",     "link")
 186     _add("HAVE_LUTIMES",    "utime")
 187     _add("HAVE_LSTAT",      "stat")
 188     _add("HAVE_FSTATAT",    "stat")
 189     _add("HAVE_UTIMENSAT",  "utime")
 190     _add("MS_WINDOWS",      "stat")
 191     supports_follow_symlinks = _set
 192
 193     del _set
 194     del _have_functions
 195     del _globals
 196     del _add
 197
 198
 199 # Python uses fixed values for the SEEK_ constants; they are mapped
 200 # to native constants if necessary in posixmodule.c
 201 # Other possible SEEK values are directly imported from posixmodule.c
 202 SEEK_SET = 0
 203 SEEK_CUR = 1
 204 SEEK_END = 2
 205
 206 # Super directory utilities.
 207 # (Inspired by Eric Raymond; the doc strings are mostly his)
 208
 209 def makedirs(name, mode=0o777, exist_ok=False):
 210     """makedirs(name [, mode=0o777][, exist_ok=False])
 211
 212     Super-mkdir; create a leaf directory and all intermediate ones.  Works like
 213     mkdir, except that any intermediate path segment (not just the rightmost)
 214     will be created if it does not exist. If the target directory already
 215     exists, raise an OSError if exist_ok is False. Otherwise no exception is
 216     raised.  This is recursive.
 217     """
 218     #makedirs(名称[,mode=0o777]][, exist_ok=False])Super-mkdir;
 219     # 创建一个叶子目录和所有中间目录。就像mkdir,除了任何中间路径段(不仅仅是最右边)
 220     # 将创建如果它不存在。如果目标目录已经存在,如果exist_ok为假,
 221     # 就启动一个OSError。否则没有例外提高。这是递归的。
 222     head, tail = path.split(name)
 223     if not tail:
 224         head, tail = path.split(head)
 225     if head and tail and not path.exists(head):
 226         try:
 227             makedirs(head, exist_ok=exist_ok)
 228         except FileExistsError:
 229             # Defeats race condition when another thread created the path
 230             #在另一个线程创建路径时击败竞争条件
 231             pass
 232         cdir = curdir
 233         if isinstance(tail, bytes):
 234             cdir = bytes(curdir, 'ASCII')
 235         if tail == cdir:           # xxx/newdir/. exists if xxx/newdir exists
 236             return
 237     try:
 238         mkdir(name, mode)
 239     except OSError:
 240         # Cannot rely on checking for EEXIST, since the operating system
 241         # could give priority to other errors like EACCES or EROFS
 242         # 不能依赖检查EEXIST,因为操作系统优先考虑其他错误,比如EACCES或EROFS
 243         if not exist_ok or not path.isdir(name):
 244             raise
 245
 246 def removedirs(name):
 247     """removedirs(name)
 248
 249     Super-rmdir; remove a leaf directory and all empty intermediate
 250     ones.  Works like rmdir except that, if the leaf directory is
 251     successfully removed, directories corresponding to rightmost path
 252     segments will be pruned away until either the whole path is
 253     consumed or an error occurs.  Errors during this latter phase are
 254     ignored -- they generally mean that a directory was not empty.
 255     """
 256     #removedirs(名字)Super-rmdir;删除一个叶子目录和所有空的中间的人。与rmdir类似,
 257     # 但叶目录除外成功删除,对应于最右边路径的目录部分将被修剪掉,直到整个路径使用或
 258     # 发生错误。后一阶段的错误是忽略——它们通常意味着目录不是空的。
 259     rmdir(name)
 260     head, tail = path.split(name)
 261     if not tail:
 262         head, tail = path.split(head)
 263     while head and tail:
 264         try:
 265             rmdir(head)
 266         except OSError:
 267             break
 268         head, tail = path.split(head)
 269
 270 def renames(old, new):
 271     """renames(old, new)
 272
 273     Super-rename; create directories as necessary and delete any left
 274     empty.  Works like rename, except creation of any intermediate
 275     directories needed to make the new pathname good is attempted
 276     first.  After the rename, directories corresponding to rightmost
 277     path segments of the old name will be pruned until either the
 278     whole path is consumed or a nonempty directory is found.
 279
 280     Note: this function can fail with the new directory structure made
 281     if you lack permissions needed to unlink the leaf directory or
 282     file.
 283     """
 284     #重命名(旧的,新的)Super-rename;根据需要创建目录并删除所有剩余的空目录。类似于
 285     # rename的工作,但是首先尝试创建任何使新路径名良好所需的中间目录。在重命名之后,
 286     # 对应于旧名称最右边路径段的目录将被删除,直到使用整个路径或找到一个非空目录为止。
 287     # 注意:如果您缺少解除叶子目录或文件链接所需的权限,那么这个函数可能会失败。
 288
 289     head, tail = path.split(new)
 290     if head and tail and not path.exists(head):
 291         makedirs(head)
 292     rename(old, new)
 293     head, tail = path.split(old)
 294     if head and tail:
 295         try:
 296             removedirs(head)
 297         except OSError:
 298             pass
 299
 300 __all__.extend(["makedirs", "removedirs", "renames"])
 301
 302 def walk(top, topdown=True, onerror=None, followlinks=False):
 303     """Directory tree generator.
 304
 305     For each directory in the directory tree rooted at top (including top
 306     itself, but excluding '.' and '..'), yields a 3-tuple
 307
 308         dirpath, dirnames, filenames
 309
 310     dirpath is a string, the path to the directory.  dirnames is a list of
 311     the names of the subdirectories in dirpath (excluding '.' and '..').
 312     filenames is a list of the names of the non-directory files in dirpath.
 313     Note that the names in the lists are just names, with no path components.
 314     To get a full path (which begins with top) to a file or directory in
 315     dirpath, do os.path.join(dirpath, name).
 316
 317     If optional arg 'topdown' is true or not specified, the triple for a
 318     directory is generated before the triples for any of its subdirectories
 319     (directories are generated top down).  If topdown is false, the triple
 320     for a directory is generated after the triples for all of its
 321     subdirectories (directories are generated bottom up).
 322
 323     When topdown is true, the caller can modify the dirnames list in-place
 324     (e.g., via del or slice assignment), and walk will only recurse into the
 325     subdirectories whose names remain in dirnames; this can be used to prune the
 326     search, or to impose a specific order of visiting.  Modifying dirnames when
 327     topdown is false is ineffective, since the directories in dirnames have
 328     already been generated by the time dirnames itself is generated. No matter
 329     the value of topdown, the list of subdirectories is retrieved before the
 330     tuples for the directory and its subdirectories are generated.
 331
 332     By default errors from the os.scandir() call are ignored.  If
 333     optional arg 'onerror' is specified, it should be a function; it
 334     will be called with one argument, an OSError instance.  It can
 335     report the error to continue with the walk, or raise the exception
 336     to abort the walk.  Note that the filename is available as the
 337     filename attribute of the exception object.
 338
 339     By default, os.walk does not follow symbolic links to subdirectories on
 340     systems that support them.  In order to get this functionality, set the
 341     optional argument 'followlinks' to true.
 342
 343     Caution:  if you pass a relative pathname for top, don't change the
 344     current working directory between resumptions of walk.  walk never
 345     changes the current directory, and assumes that the client doesn't
 346     either.
 347
 348     Example:
 349
 350     import os
 351     from os.path import join, getsize
 352     for root, dirs, files in os.walk('python/Lib/email'):
 353         print(root, "consumes", end="")
 354         print(sum([getsize(join(root, name)) for name in files]), end="")
 355         print("bytes in", len(files), "non-directory files")
 356         if 'CVS' in dirs:
 357             dirs.remove('CVS')  # don't visit CVS directories
 358     """
 359     #目录树生成器。对于根在顶部的目录树中的每个目录(包括顶部本身,但不包括')。,
 360     # 生成一个3元组dirpath, dirnames, filenames dirpath是一个字符串,目录路径。
 361     # dirnames是dirpath(不包括')中子目录的名称列表。”和“…”)。filenames文件名是
 362     # dirpath中非目录文件的名称列表。注意,列表中的名称只是名称,没有路径组件。
 363     # 要获得指向dirpath文件或目录的完整路径(从顶部开始),请使用os.path。加入
 364     # (dirpath、名称)。如果可选的arg '自顶向下'为真或未指定,则目录的三元组在其任何
 365     # 子目录的三元组之前生成(目录自顶向下生成)。如果自顶向下为false,目录的三元组将
 366     # 在所有子目录的三元组之后生成(从下往上生成目录)。当topdown为真时,调用者可以就
 367     # 地修改dirnames列表(例如,通过del或slice赋值),walk只会递归到名称仍然为
 368     # dirnames的子目录中;这可以用于删除搜索,或强制执行特定的访问顺序。当自顶向下为
 369     # false时修改dirnames是无效的,因为在生成dirnames本身时,dirnames中的目录已经
 370     # 生成了。无论自顶向下的值是多少,子目录列表都会在生成目录及其子目录的元组之前被
 371     # 检索。默认情况下,os.scandir()调用的错误将被忽略。如果指定了可选的arg
 372     # 'onerror',它应该是一个函数;它将使用一个参数调用,一个OSError实例。它可以报
 373     # 告错误以继续遍历,或者引发异常以中止遍历。注意,文件名作为异常对象的filename
 374     # 属性可用。默认情况下,操作系统。walk不会跟随支持它的系统上子目录的符号链接。
 375     # 为了获得这个功能,将可选参数“followlinks”设置为true。注意:如果您为top传递了
 376     # 一个相对路径名,那么不要在walk的恢复之间更改当前的工作目录。walk从不更改当前
 377     # 目录,并且假设客户机也不更改。
 378
 379     top = fspath(top)
 380     dirs = []
 381     nondirs = []
 382     walk_dirs = []
 383
 384     # We may not have read permission for top, in which case we can't
 385     # get a list of the files the directory contains.  os.walk
 386     # always suppressed the exception then, rather than blow up for a
 387     # minor reason when (say) a thousand readable directories are still
 388     # left to visit.  That logic is copied here.
 389     #我们可能没有top的读权限,在这种情况下,我们无法获得目录包含的文件列表。操作系统。
 390     # 那时,walk总是会抑制异常,而不是因为一个小原因(比如)当仍有1000个可读目录要访
 391     # 问时就会崩溃。这里复制了这个逻辑。
 392
 393     try:
 394         # Note that scandir is global in this module due
 395         # to earlier import-*.
 396         #注意,由于前面的import-*, scandir在这个模块中是全局的。
 397         scandir_it = scandir(top)
 398     except OSError as error:
 399         if onerror is not None:
 400             onerror(error)
 401         return
 402
 403     with scandir_it:
 404         while True:
 405             try:
 406                 try:
 407                     entry = next(scandir_it)
 408                 except StopIteration:
 409                     break
 410             except OSError as error:
 411                 if onerror is not None:
 412                     onerror(error)
 413                 return
 414
 415             try:
 416                 is_dir = entry.is_dir()
 417             except OSError:
 418                 # If is_dir() raises an OSError, consider that the entry is not
 419                 # a directory, same behaviour than os.path.isdir().
 420                 #如果is_dir()引发一个OSError,则考虑该条目不是一个目录,其行为与os.path.isdir()相同
 421                 is_dir = False
 422
 423             if is_dir:
 424                 dirs.append(entry.name)
 425             else:
 426                 nondirs.append(entry.name)
 427
 428             if not topdown and is_dir:
 429                 # Bottom-up: recurse into sub-directory, but exclude symlinks to
 430                 # directories if followlinks is False
 431                 #自底向上:递归到子目录中,但如果followlinks为False,则排除到目录的符号链接
 432                 if followlinks:
 433                     walk_into = True
 434                 else:
 435                     try:
 436                         is_symlink = entry.is_symlink()
 437                     except OSError:
 438                         # If is_symlink() raises an OSError, consider that the
 439                         # entry is not a symbolic link, same behaviour than
 440                         # os.path.islink().
 441                         #如果is_symlink()引发一个OSError,请考虑该条目不是一个符号链接,其行为
 442                         # 与os.path.islink()相同。
 443
 444                         is_symlink = False
 445                     walk_into = not is_symlink
 446
 447                 if walk_into:
 448                     walk_dirs.append(entry.path)
 449
 450     # Yield before recursion if going top down 如果从上到下递归,在递归之前要先屈服
 451     if topdown:
 452         yield top, dirs, nondirs
 453
 454         # Recurse into sub-directories 递归到子目录
 455         islink, join = path.islink, path.join
 456         for dirname in dirs:
 457             new_path = join(top, dirname)
 458             # Issue #23605: os.path.islink() is used instead of caching
 459             # entry.is_symlink() result during the loop on os.scandir() because
 460             # the caller can replace the directory entry during the "yield"
 461             # above.
 462             #问题#23605:使用os.path.islink()来替代cache .is_symlink()结果,因为调用者
 463             # 可以在“yield”中替换目录条目。
 464
 465             if followlinks or not islink(new_path):
 466                 yield from walk(new_path, topdown, onerror, followlinks)
 467     else:
 468         # Recurse into sub-directories
 469         for new_path in walk_dirs:
 470             yield from walk(new_path, topdown, onerror, followlinks)
 471         # Yield after recursion if going bottom up 如果从下往上递归,则在递归后屈服
 472         yield top, dirs, nondirs
 473
 474 __all__.append("walk")
 475
 476 if {open, stat} <= supports_dir_fd and {scandir, stat} <= supports_fd:
 477
 478     def fwalk(top=".", topdown=True, onerror=None, *, follow_symlinks=False, dir_fd=None):
 479         """Directory tree generator.
 480
 481         This behaves exactly like walk(), except that it yields a 4-tuple
 482
 483             dirpath, dirnames, filenames, dirfd
 484
 485         `dirpath`, `dirnames` and `filenames` are identical to walk() output,
 486         and `dirfd` is a file descriptor referring to the directory `dirpath`.
 487
 488         The advantage of fwalk() over walk() is that it's safe against symlink
 489         races (when follow_symlinks is False).
 490
 491         If dir_fd is not None, it should be a file descriptor open to a directory,
 492           and top should be relative; top will then be relative to that directory.
 493           (dir_fd is always supported for fwalk.)
 494
 495         Caution:
 496         Since fwalk() yields file descriptors, those are only valid until the
 497         next iteration step, so you should dup() them if you want to keep them
 498         for a longer period.
 499
 500         Example:
 501
 502         import os
 503         for root, dirs, files, rootfd in os.fwalk('python/Lib/email'):
 504             print(root, "consumes", end="")
 505             print(sum([os.stat(name, dir_fd=rootfd).st_size for name in files]),
 506                   end="")
 507             print("bytes in", len(files), "non-directory files")
 508             if 'CVS' in dirs:
 509                 dirs.remove('CVS')  # don't visit CVS directories
 510         """
 511         #目录树生成器。它的行为与walk()完全相同,只是它产生了一个4元组dirpath、
 512         # dirnames、filenames、dirfd ' dirpath '、' dirnames '和' filenames
 513         # '与walk()输出相同,而' dirfd '是一个指向目录' dirpath '的文件描述符。
 514         # 与walk()相比,fwalk()的优点是它对于symlink race(当follow_symlinks为False时)
 515         # 是安全的。如果dir_fd不是None,它应该是打开到目录的文件描述符,top应该是相对的;
 516         # 然后top将相对于那个目录。(fwalk始终支持dir_fd。)注意:因为fwalk()产生了文件描述符,
 517         # 所以这些描述符只在下一个迭代步骤之前有效,所以如果您想长时间保存它们,您应该使用dup()。
 518
 519         if not isinstance(top, int) or not hasattr(top, '__index__'):
 520             top = fspath(top)
 521         # Note: To guard against symlink races, we use the standard
 522         # lstat()/open()/fstat() trick.
 523         #注意:为了防止符号链接竞争,我们使用标准的lstat()/open()/fstat()技巧。
 524         if not follow_symlinks:
 525             orig_st = stat(top, follow_symlinks=False, dir_fd=dir_fd)
 526         topfd = open(top, O_RDONLY, dir_fd=dir_fd)
 527         try:
 528             if (follow_symlinks or (st.S_ISDIR(orig_st.st_mode) and
 529                                     path.samestat(orig_st, stat(topfd)))):
 530                 yield from _fwalk(topfd, top, isinstance(top, bytes),
 531                                   topdown, onerror, follow_symlinks)
 532         finally:
 533             close(topfd)
 534
 535     def _fwalk(topfd, toppath, isbytes, topdown, onerror, follow_symlinks):
 536         # Note: This uses O(depth of the directory tree) file descriptors: if
 537         # necessary, it can be adapted to only require O(1) FDs, see issue
 538         # #13734.
 539         #注意:这使用了O(目录树的深度)文件描述符:如果需要,它可以被修改为只需要O(1) FDs,请参阅issue13734
 540
 541         scandir_it = scandir(topfd)
 542         dirs = []
 543         nondirs = []
 544         entries = None if topdown or follow_symlinks else []
 545         for entry in scandir_it:
 546             name = entry.name
 547             if isbytes:
 548                 name = fsencode(name)
 549             try:
 550                 if entry.is_dir():
 551                     dirs.append(name)
 552                     if entries is not None:
 553                         entries.append(entry)
 554                 else:
 555                     nondirs.append(name)
 556             except OSError:
 557                 try:
 558                     # Add dangling symlinks, ignore disappeared files
 559                     #添加悬空符号链接,忽略消失的文件
 560                     if entry.is_symlink():
 561                         nondirs.append(name)
 562                 except OSError:
 563                     pass
 564
 565         if topdown:
 566             yield toppath, dirs, nondirs, topfd
 567
 568         for name in dirs if entries is None else zip(dirs, entries):
 569             try:
 570                 if not follow_symlinks:
 571                     if topdown:
 572                         orig_st = stat(name, dir_fd=topfd, follow_symlinks=False)
 573                     else:
 574                         assert entries is not None
 575                         name, entry = name
 576                         orig_st = entry.stat(follow_symlinks=False)
 577                 dirfd = open(name, O_RDONLY, dir_fd=topfd)
 578             except OSError as err:
 579                 if onerror is not None:
 580                     onerror(err)
 581                 continue
 582             try:
 583                 if follow_symlinks or path.samestat(orig_st, stat(dirfd)):
 584                     dirpath = path.join(toppath, name)
 585                     yield from _fwalk(dirfd, dirpath, isbytes,
 586                                       topdown, onerror, follow_symlinks)
 587             finally:
 588                 close(dirfd)
 589
 590         if not topdown:
 591             yield toppath, dirs, nondirs, topfd
 592
 593     __all__.append("fwalk")
 594
 595 # Make sure os.environ exists, at least
 596 #确os.environ至少是存在的
 597 try:
 598     environ
 599 except NameError:
 600     environ = {}
 601
 602 def execl(file, *args):
 603     """execl(file, *args)
 604
 605     Execute the executable file with argument list args, replacing the
 606     current process. """
 607     #execl(文件,*args)用参数列表args执行可执行文件,替换当前进程。
 608     execv(file, args)
 609
 610 def execle(file, *args):
 611     """execle(file, *args, env)
 612
 613     Execute the executable file with argument list args and
 614     environment env, replacing the current process. """
 615     #execle(文件,*args, env)用参数列表args和环境env执行可执行文件,替换当前进程。
 616     env = args[-1]
 617     execve(file, args[:-1], env)
 618
 619 def execlp(file, *args):
 620     """execlp(file, *args)
 621
 622     Execute the executable file (which is searched for along $PATH)
 623     with argument list args, replacing the current process. """
 624     #execlp(文件,*args)用参数列表args执行可执行文件(沿着$PATH搜索),替换当前进程。
 625     execvp(file, args)
 626
 627 def execlpe(file, *args):
 628     """execlpe(file, *args, env)
 629
 630     Execute the executable file (which is searched for along $PATH)
 631     with argument list args and environment env, replacing the current
 632     process. """
 633     #execlpe(文件,*args, env)用参数列表arg和环境env执行可执行文件(沿着$PATH搜索),
 634     # 替换当前进程。
 635
 636     env = args[-1]
 637     execvpe(file, args[:-1], env)
 638
 639 def execvp(file, args):
 640     """execvp(file, args)
 641
 642     Execute the executable file (which is searched for along $PATH)
 643     with argument list args, replacing the current process.
 644     args may be a list or tuple of strings. """
 645     #execvp(文件,args)用参数列表args执行可执行文件(沿着$PATH搜索),替换当前进程。
 646     # args可以是字符串的列表或元组。
 647     _execvpe(file, args)
 648
 649 def execvpe(file, args, env):
 650     """execvpe(file, args, env)
 651
 652     Execute the executable file (which is searched for along $PATH)
 653     with argument list args and environment env , replacing the
 654     current process.
 655     args may be a list or tuple of strings. """
 656     #execvpe(文件,args, env)用参数列表arg和环境env执行可执行文件(沿着$PATH搜索),
 657     # 替换当前进程。args可以是字符串的列表或元组。
 658     _execvpe(file, args, env)
 659
 660 __all__.extend(["execl","execle","execlp","execlpe","execvp","execvpe"])
 661
 662 def _execvpe(file, args, env=None):
 663     if env is not None:
 664         exec_func = execve
 665         argrest = (args, env)
 666     else:
 667         exec_func = execv
 668         argrest = (args,)
 669         env = environ
 670
 671     if path.dirname(file):
 672         exec_func(file, *argrest)
 673         return
 674     saved_exc = None
 675     path_list = get_exec_path(env)
 676     if name != 'nt':
 677         file = fsencode(file)
 678         path_list = map(fsencode, path_list)
 679     for dir in path_list:
 680         fullname = path.join(dir, file)
 681         try:
 682             exec_func(fullname, *argrest)
 683         except (FileNotFoundError, NotADirectoryError) as e:
 684             last_exc = e
 685         except OSError as e:
 686             last_exc = e
 687             if saved_exc is None:
 688                 saved_exc = e
 689     if saved_exc is not None:
 690         raise saved_exc
 691     raise last_exc
 692
 693
 694 def get_exec_path(env=None):
 695     """Returns the sequence of directories that will be searched for the
 696     named executable (similar to a shell) when launching a process.
 697
 698     *env* must be an environment variable dict or None.  If *env* is None,
 699     os.environ will be used.
 700     """
 701     #返回在启动进程时将搜索命名可执行文件(类似于shell)的目录序列。*env*必须是环境变量dict或无。
 702     # 如果*env*为空,操作系统。将使用环境。
 703
 704     # Use a local import instead of a global import to limit the number of
 705     # modules loaded at startup: the os module is always loaded at startup by
 706     # Python. It may also avoid a bootstrap issue.
 707     #使用本地导入而不是全局导入来限制在启动时加载的模块数量:os模块总是在启动时
 708     # 由Python加载。它还可以避免引导问题。
 709     import warnings
 710
 711     if env is None:
 712         env = environ
 713
 714     # {b'PATH': ...}.get('PATH') and {'PATH': ...}.get(b'PATH') emit a
 715     # BytesWarning when using python -b or python -bb: ignore the warning
 716     with warnings.catch_warnings():
 717         warnings.simplefilter("ignore", BytesWarning)
 718
 719         try:
 720             path_list = env.get('PATH')
 721         except TypeError:
 722             path_list = None
 723
 724         if supports_bytes_environ:
 725             try:
 726                 path_listb = env[b'PATH']
 727             except (KeyError, TypeError):
 728                 pass
 729             else:
 730                 if path_list is not None:
 731                     raise ValueError(
 732                         "env cannot contain 'PATH' and b'PATH' keys")
 733                 path_list = path_listb
 734
 735             if path_list is not None and isinstance(path_list, bytes):
 736                 path_list = fsdecode(path_list)
 737
 738     if path_list is None:
 739         path_list = defpath
 740     return path_list.split(pathsep)
 741
 742
 743 # Change environ to automatically call putenv(), unsetenv if they exist.
 744 #改变环境自动调用putenv(), unsetenv如果它们存在。
 745 from _collections_abc import MutableMapping
 746
 747 class _Environ(MutableMapping):
 748     def __init__(self, data, encodekey, decodekey, encodevalue, decodevalue, putenv, unsetenv):
 749         self.encodekey = encodekey
 750         self.decodekey = decodekey
 751         self.encodevalue = encodevalue
 752         self.decodevalue = decodevalue
 753         self.putenv = putenv
 754         self.unsetenv = unsetenv
 755         self._data = data
 756
 757     def __getitem__(self, key):
 758         try:
 759             value = self._data[self.encodekey(key)]
 760         except KeyError:
 761             # raise KeyError with the original key value
 762             raise KeyError(key) from None
 763         return self.decodevalue(value)
 764
 765     def __setitem__(self, key, value):
 766         key = self.encodekey(key)
 767         value = self.encodevalue(value)
 768         self.putenv(key, value)
 769         self._data[key] = value
 770
 771     def __delitem__(self, key):
 772         encodedkey = self.encodekey(key)
 773         self.unsetenv(encodedkey)
 774         try:
 775             del self._data[encodedkey]
 776         except KeyError:
 777             # raise KeyError with the original key value 使用原始键值引发KeyError
 778             raise KeyError(key) from None
 779
 780     def __iter__(self):
 781         # list() from dict object is an atomic operation
 782         #dict对象的list()是一个原子操作
 783         keys = list(self._data)
 784         for key in keys:
 785             yield self.decodekey(key)
 786
 787     def __len__(self):
 788         return len(self._data)
 789
 790     def __repr__(self):
 791         return 'environ({{{}}})'.format(', '.join(
 792             ('{!r}: {!r}'.format(self.decodekey(key), self.decodevalue(value))
 793             for key, value in self._data.items())))
 794
 795     def copy(self):
 796         return dict(self)
 797
 798     def setdefault(self, key, value):
 799         if key not in self:
 800             self[key] = value
 801         return self[key]
 802
 803 try:
 804     _putenv = putenv
 805 except NameError:
 806     _putenv = lambda key, value: None
 807 else:
 808     if "putenv" not in __all__:
 809         __all__.append("putenv")
 810
 811 try:
 812     _unsetenv = unsetenv
 813 except NameError:
 814     _unsetenv = lambda key: _putenv(key, "")
 815 else:
 816     if "unsetenv" not in __all__:
 817         __all__.append("unsetenv")
 818
 819 def _createenviron():
 820     if name == 'nt':
 821         # Where Env Var Names Must Be UPPERCASE 在哪里Env Var名称必须是大写的
 822         def check_str(value):
 823             if not isinstance(value, str):
 824                 raise TypeError("str expected, not %s" % type(value).__name__)
 825             return value
 826         encode = check_str
 827         decode = str
 828         def encodekey(key):
 829             return encode(key).upper()
 830         data = {}
 831         for key, value in environ.items():
 832             data[encodekey(key)] = value
 833     else:
 834         # Where Env Var Names Can Be Mixed Case
 835         encoding = sys.getfilesystemencoding()
 836         def encode(value):
 837             if not isinstance(value, str):
 838                 raise TypeError("str expected, not %s" % type(value).__name__)
 839             return value.encode(encoding, 'surrogateescape')
 840         def decode(value):
 841             return value.decode(encoding, 'surrogateescape')
 842         encodekey = encode
 843         data = environ
 844     return _Environ(data,
 845         encodekey, decode,
 846         encode, decode,
 847         _putenv, _unsetenv)
 848
 849 # unicode environ
 850 environ = _createenviron()
 851 del _createenviron
 852
 853
 854 def getenv(key, default=None):
 855     """Get an environment variable, return None if it doesn't exist.
 856     The optional second argument can specify an alternate default.
 857     key, default and the result are str."""
 858     #获取一个环境变量,如果它不存在,返回None。可选的第二个参数可以指定另一个默认值。
 859     # 键、默认值和结果都是str。
 860
 861     return environ.get(key, default)
 862
 863 supports_bytes_environ = (name != 'nt')
 864 __all__.extend(("getenv", "supports_bytes_environ"))
 865
 866 if supports_bytes_environ:
 867     def _check_bytes(value):
 868         if not isinstance(value, bytes):
 869             raise TypeError("bytes expected, not %s" % type(value).__name__)
 870         return value
 871
 872     # bytes environ
 873     environb = _Environ(environ._data,
 874         _check_bytes, bytes,
 875         _check_bytes, bytes,
 876         _putenv, _unsetenv)
 877     del _check_bytes
 878
 879     def getenvb(key, default=None):
 880         """Get an environment variable, return None if it doesn't exist.
 881         The optional second argument can specify an alternate default.
 882         key, default and the result are bytes."""
 883         #获取一个环境变量,如果它不存在,返回None。可选的第二个参数可以指定另一个默认值。
 884         # 键、默认值和结果都是字节。
 885
 886         return environb.get(key, default)
 887
 888     __all__.extend(("environb", "getenvb"))
 889
 890 def _fscodec():
 891     encoding = sys.getfilesystemencoding()
 892     errors = sys.getfilesystemencodeerrors()
 893
 894     def fsencode(filename):
 895         """Encode filename (an os.PathLike, bytes, or str) to the filesystem
 896         encoding with 'surrogateescape' error handler, return bytes unchanged.
 897         On Windows, use 'strict' error handler if the file system encoding is
 898         'mbcs' (which is the default encoding).
 899         """
 900         #编码文件名(一个操作系统)。使用“surrogateescape”错误处理程序对文件系统进行
 901         # 编码,返回字节不变。在Windows上,如果文件系统编码是“mbcs”(这是默认编码),
 902         # 则使用“严格”错误处理程序。
 903
 904         filename = fspath(filename)  # Does type-checking of `filename`.
 905         if isinstance(filename, str):
 906             return filename.encode(encoding, errors)
 907         else:
 908             return filename
 909
 910     def fsdecode(filename):
 911         """Decode filename (an os.PathLike, bytes, or str) from the filesystem
 912         encoding with 'surrogateescape' error handler, return str unchanged. On
 913         Windows, use 'strict' error handler if the file system encoding is
 914         'mbcs' (which is the default encoding).
 915         """
 916         #解码文件名(一个操作系统)。从带有“surrogateescape”错误处理程序的文件系统编码中,
 917         # 返回str不变。在Windows上,如果文件系统编码是“mbcs”(这是默认编码),则使用
 918         # “严格”错误处理程序。
 919
 920         filename = fspath(filename)  # Does type-checking of `filename`.
 921         if isinstance(filename, bytes):
 922             return filename.decode(encoding, errors)
 923         else:
 924             return filename
 925
 926     return fsencode, fsdecode
 927
 928 fsencode, fsdecode = _fscodec()
 929 del _fscodec
 930
 931 # Supply spawn*() (probably only for Unix) 提供spawn*()(可能只适用于Unix)
 932 if _exists("fork") and not _exists("spawnv") and _exists("execv"):
 933
 934     P_WAIT = 0
 935     P_NOWAIT = P_NOWAITO = 1
 936
 937     __all__.extend(["P_WAIT", "P_NOWAIT", "P_NOWAITO"])
 938
 939     # XXX Should we support P_DETACH?  I suppose it could fork()**2
 940     # and close the std I/O streams.  Also, P_OVERLAY is the same
 941     # as execv*()?
 942     #我们应该支持P_DETACH吗?我想它可以分叉()**2并关闭std I/O流。另外,P_OVERLAY和execv*()一样?
 943
 944     def _spawnvef(mode, file, args, env, func):
 945         # Internal helper; func is the exec*() function to use
 946         #内部辅助;func是要使用的exec*()函数
 947         if not isinstance(args, (tuple, list)):
 948             raise TypeError('argv must be a tuple or a list')
 949         if not args or not args[0]:
 950             raise ValueError('argv first element cannot be empty')
 951         pid = fork()
 952         if not pid:
 953             # Child
 954             try:
 955                 if env is None:
 956                     func(file, args)
 957                 else:
 958                     func(file, args, env)
 959             except:
 960                 _exit(127)
 961         else:
 962             # Parent
 963             if mode == P_NOWAIT:
 964                 return pid # Caller is responsible for waiting!
 965             while 1:
 966                 wpid, sts = waitpid(pid, 0)
 967                 if WIFSTOPPED(sts):
 968                     continue
 969                 elif WIFSIGNALED(sts):
 970                     return -WTERMSIG(sts)
 971                 elif WIFEXITED(sts):
 972                     return WEXITSTATUS(sts)
 973                 else:
 974                     raise OSError("Not stopped, signaled or exited???")
 975
 976     def spawnv(mode, file, args):
 977         """spawnv(mode, file, args) -> integer
 978
 979 Execute file with arguments from args in a subprocess.
 980 If mode == P_NOWAIT return the pid of the process.
 981 If mode == P_WAIT return the process's exit code if it exits normally;
 982 otherwise return -SIG, where SIG is the signal that killed it. """
 983         #在子进程中使用args参数执行文件。If mode == P_NOWAIT返回进程的pid。
 984         # 如果mode == P_WAIT返回进程正常退出的退出代码;否则返回-SIG,其中SIG是终止
 985         # 进程的信号。
 986
 987         return _spawnvef(mode, file, args, None, execv)
 988
 989     def spawnve(mode, file, args, env):
 990         """spawnve(mode, file, args, env) -> integer
 991
 992 Execute file with arguments from args in a subprocess with the
 993 specified environment.
 994 If mode == P_NOWAIT return the pid of the process.
 995 If mode == P_WAIT return the process's exit code if it exits normally;
 996 otherwise return -SIG, where SIG is the signal that killed it. """
 997         #使用指定环境的子进程中的args参数执行文件。If mode == P_NOWAIT返回进程的pid。
 998         # 如果mode == P_WAIT返回进程正常退出的退出代码;否则返回-SIG,其中SIG是终止进程
 999         # 的信号。
1000
1001         return _spawnvef(mode, file, args, env, execve)
1002
1003     # Note: spawnvp[e] isn't currently supported on Windows
1004
1005     def spawnvp(mode, file, args):
1006         """spawnvp(mode, file, args) -> integer
1007
1008 Execute file (which is looked for along $PATH) with arguments from
1009 args in a subprocess.
1010 If mode == P_NOWAIT return the pid of the process.
1011 If mode == P_WAIT return the process's exit code if it exits normally;
1012 otherwise return -SIG, where SIG is the signal that killed it. """
1013         return _spawnvef(mode, file, args, None, execvp)
1014
1015     def spawnvpe(mode, file, args, env):
1016         """spawnvpe(mode, file, args, env) -> integer
1017
1018 Execute file (which is looked for along $PATH) with arguments from
1019 args in a subprocess with the supplied environment.
1020 If mode == P_NOWAIT return the pid of the process.
1021 If mode == P_WAIT return the process's exit code if it exits normally;
1022 otherwise return -SIG, where SIG is the signal that killed it. """
1023         return _spawnvef(mode, file, args, env, execvpe)
1024
1025
1026     __all__.extend(["spawnv", "spawnve", "spawnvp", "spawnvpe"])
1027
1028
1029 if _exists("spawnv"):
1030     # These aren't supplied by the basic Windows code
1031     # but can be easily implemented in Python
1032
1033     def spawnl(mode, file, *args):
1034         """spawnl(mode, file, *args) -> integer
1035
1036 Execute file with arguments from args in a subprocess.
1037 If mode == P_NOWAIT return the pid of the process.
1038 If mode == P_WAIT return the process's exit code if it exits normally;
1039 otherwise return -SIG, where SIG is the signal that killed it. """
1040         return spawnv(mode, file, args)
1041
1042     def spawnle(mode, file, *args):
1043         """spawnle(mode, file, *args, env) -> integer
1044
1045 Execute file with arguments from args in a subprocess with the
1046 supplied environment.
1047 If mode == P_NOWAIT return the pid of the process.
1048 If mode == P_WAIT return the process's exit code if it exits normally;
1049 otherwise return -SIG, where SIG is the signal that killed it. """
1050         env = args[-1]
1051         return spawnve(mode, file, args[:-1], env)
1052
1053
1054     __all__.extend(["spawnl", "spawnle"])
1055
1056
1057 if _exists("spawnvp"):
1058     # At the moment, Windows doesn't implement spawnvp[e],
1059     # so it won't have spawnlp[e] either.
1060     def spawnlp(mode, file, *args):
1061         """spawnlp(mode, file, *args) -> integer
1062
1063 Execute file (which is looked for along $PATH) with arguments from
1064 args in a subprocess with the supplied environment.
1065 If mode == P_NOWAIT return the pid of the process.
1066 If mode == P_WAIT return the process's exit code if it exits normally;
1067 otherwise return -SIG, where SIG is the signal that killed it. """
1068         return spawnvp(mode, file, args)
1069
1070     def spawnlpe(mode, file, *args):
1071         """spawnlpe(mode, file, *args, env) -> integer
1072
1073 Execute file (which is looked for along $PATH) with arguments from
1074 args in a subprocess with the supplied environment.
1075 If mode == P_NOWAIT return the pid of the process.
1076 If mode == P_WAIT return the process's exit code if it exits normally;
1077 otherwise return -SIG, where SIG is the signal that killed it. """
1078         env = args[-1]
1079         return spawnvpe(mode, file, args[:-1], env)
1080
1081
1082     __all__.extend(["spawnlp", "spawnlpe"])
1083
1084
1085 # Supply os.popen()
1086 def popen(cmd, mode="r", buffering=-1):
1087     if not isinstance(cmd, str):
1088         raise TypeError("invalid cmd type (%s, expected string)" % type(cmd))
1089     if mode not in ("r", "w"):
1090         raise ValueError("invalid mode %r" % mode)
1091     if buffering == 0 or buffering is None:
1092         raise ValueError("popen() does not support unbuffered streams")
1093     import subprocess, io
1094     if mode == "r":
1095         proc = subprocess.Popen(cmd,
1096                                 shell=True,
1097                                 stdout=subprocess.PIPE,
1098                                 bufsize=buffering)
1099         return _wrap_close(io.TextIOWrapper(proc.stdout), proc)
1100     else:
1101         proc = subprocess.Popen(cmd,
1102                                 shell=True,
1103                                 stdin=subprocess.PIPE,
1104                                 bufsize=buffering)
1105         return _wrap_close(io.TextIOWrapper(proc.stdin), proc)
1106
1107 # Helper for popen() -- a proxy for a file whose close waits for the process
1108 class _wrap_close:
1109     def __init__(self, stream, proc):
1110         self._stream = stream
1111         self._proc = proc
1112     def close(self):
1113         self._stream.close()
1114         returncode = self._proc.wait()
1115         if returncode == 0:
1116             return None
1117         if name == 'nt':
1118             return returncode
1119         else:
1120             return returncode << 8  # Shift left to match old behavior
1121     def __enter__(self):
1122         return self
1123     def __exit__(self, *args):
1124         self.close()
1125     def __getattr__(self, name):
1126         return getattr(self._stream, name)
1127     def __iter__(self):
1128         return iter(self._stream)
1129
1130 # Supply os.fdopen()
1131 def fdopen(fd, *args, **kwargs):
1132     if not isinstance(fd, int):
1133         raise TypeError("invalid fd type (%s, expected integer)" % type(fd))
1134     import io
1135     return io.open(fd, *args, **kwargs)
1136
1137
1138 # For testing purposes, make sure the function is available when the C
1139 # implementation exists.
1140 def _fspath(path):
1141     """Return the path representation of a path-like object.
1142
1143     If str or bytes is passed in, it is returned unchanged. Otherwise the
1144     os.PathLike interface is used to get the path representation. If the
1145     path representation is not str or bytes, TypeError is raised. If the
1146     provided path is not str, bytes, or os.PathLike, TypeError is raised.
1147     """
1148     #返回类路径对象的路径表示。如果传入str或字节,则返回时不会改变。否则,操作系统。
1149     # 类路径接口用于获取路径表示。如果路径表示不是str或字节,则会引发类型错误。如果
1150     # 提供的路径不是str、字节或os。类路径,类型错误。
1151
1152     if isinstance(path, (str, bytes)):
1153         return path
1154
1155     # Work from the object's type to match method resolution of other magic
1156     # methods.
1157     #从对象的类型开始工作,以匹配其他魔术方法的方法解析。
1158     path_type = type(path)
1159     try:
1160         path_repr = path_type.__fspath__(path)
1161     except AttributeError:
1162         if hasattr(path_type, '__fspath__'):
1163             raise
1164         else:
1165             raise TypeError("expected str, bytes or os.PathLike object, "
1166                             "not " + path_type.__name__)
1167     if isinstance(path_repr, (str, bytes)):
1168         return path_repr
1169     else:
1170         raise TypeError("expected {}.__fspath__() to return str or bytes, "
1171                         "not {}".format(path_type.__name__,
1172                                         type(path_repr).__name__))
1173
1174 # If there is no C implementation, make the pure Python version the
1175 # implementation as transparently as possible.
1176 #如果没有C实现,请尽可能使纯Python版本的实现透明。
1177 if not _exists('fspath'):
1178     fspath = _fspath
1179     fspath.__name__ = "fspath"
1180
1181
1182 class PathLike(abc.ABC):
1183
1184     """Abstract base class for implementing the file system path protocol."""
1185     #用于实现文件系统路径协议的抽象基类。
1186
1187     @abc.abstractmethod
1188     def __fspath__(self):
1189         """Return the file system path representation of the object."""
1190         #返回对象的文件系统路径表示。
1191         raise NotImplementedError
1192
1193     @classmethod
1194     def __subclasshook__(cls, subclass):
1195         return hasattr(subclass, '__fspath__')
os源代码.py
  • re模块:
'''re模块'''
import re
res = re.match("^lizi\d+6","lizi8888088886")  #^代表以什么开头,\d表示数字,"."表示任意,"+"表示多个
res1 = re.match("^.+","lizi8888088886")   #"^.+"代表任意匹配多个字符
print(res)
print(res1)
print(res.group())
print(res1.group())

"$"
#匹配结尾
# res = re.match(".+","lizi8888088886")
# print(res.group())

# res = re.search("#.+#","lizi88fgh#good#fg89")
# res = re.search("[0-9]+","lizi88fgh#good#fg89")
# res = re.search("[0-9]{1,4}","lizi88fgh#good#fg89")
# print(res.group())
# print(res)

# res = re.findall("","")

# s = "abcd1234###hlizi@34"
# res = re.search("(?P<id>[0-9]+)(?P<name>[a-z]+)",s)
# res1 = re.search("(?P<name>lizi)",s)
# print(res.groupdict())
# print(res1.groupdict())

# res = re.split("[0-9]",s)
# res = re.split("[0-9]+",s)
# res = re.sub("[0-9]+","|",s)

# print(res)
Python   模块-LMLPHPPython   模块-LMLPHP
  1 # Secret Labs' Regular Expression Engine
  2 #Secret Labs的正则表达式引擎
  3 # re-compatible interface for the sre matching engine
  4 #sre匹配引擎的重新兼容接口
  5 # Copyright (c) 1998-2001 by Secret Labs AB.  All rights reserved.
  6 #版权所有(c) 1998-2001
  7 # This version of the SRE library can be redistributed under CNRI's
  8 # Python 1.6 license.  For any other use, please contact Secret Labs
  9 # AB (info@pythonware.com).
 10 #这个版本的SRE库可以在CNRI的Python 1.6许可证下重新发布。
 11 # 如有其他用途,请联系Secret Labs AB (info@pythonware.com)。
 12 # Portions of this engine have been developed in cooperation with
 13 # CNRI.  Hewlett-Packard provided funding for 1.6 integration and
 14 # other compatibility work.
 15 #该发动机的部分部件是与CNRI公司合作开发的。惠普为1.6集成和其他兼容性工作提供了资金
 16
 17 r"""Support for regular expressions (RE).  #支持正则表达式(RE)。
 18
 19 This module provides regular expression matching operations similar to
 20 those found in Perl.  It supports both 8-bit and Unicode strings; both
 21 the pattern and the strings being processed can contain null bytes and
 22 characters outside the US ASCII range.
 23 #这个模块提供了与下面类似的正则表达式匹配操作在Perl中找到的。
 24 它支持8位和Unicode字符串;这两个正在处理的模式和字符串可以包含空字节和
 25 美国ASCII范围以外的字符。
 26
 27 Regular expressions can contain both special and ordinary characters.
 28 Most ordinary characters, like "A", "a", or "0", are the simplest
 29 regular expressions; they simply match themselves.  You can
 30 concatenate ordinary characters, so last matches the string 'last'.
 31 #正则表达式可以包含特殊字符和普通字符。大多数普通字符,
 32 如“A”、“a”或“0”,都是最简单的正则表达式;他们只是匹配自己。
 33 你可以连接普通字符,最后匹配字符串'last'。
 34
 35
 36 The special characters are:
 37 #特别的字符是:
 38     "."      Matches any character except a newline.
 39              #匹配除换行符之外的任何字符。
 40
 41     "^"      Matches the start of the string.
 42              #匹配字符串的开头。
 43
 44     "$"      Matches the end of the string or just before the newline at
 45              the end of the string.
 46              #匹配字符串的末尾或在换行符at之前弦的末端
 47
 48     "*"      Matches 0 or more (greedy) repetitions of the preceding RE.
 49              Greedy means that it will match as many repetitions as possible.
 50              #匹配前面RE的0个或多个(贪婪的)重复。贪婪意味着它将匹配尽可能多的重复。
 51
 52     "+"      Matches 1 or more (greedy) repetitions of the preceding RE.
 53              #匹配前面RE的一个或多个(贪婪的)重复。
 54
 55     "?"      Matches 0 or 1 (greedy) of the preceding RE.
 56              #匹配前一个RE的0或1(贪婪)。
 57
 58     *?,+?,?? Non-greedy versions of the previous three special characters.
 59              #前三个特殊字符的非贪婪版本。
 60
 61     {m,n}    Matches from m to n repetitions of the preceding RE.
 62              #匹配前一个RE的m到n个重复。
 63
 64     {m,n}?   Non-greedy version of the above.
 65              #非贪婪版的上面。
 66
 67     "\\"     Either escapes special characters or signals a special sequence.
 68              #转义特殊字符或表示特殊序列。
 69
 70     []       Indicates a set of characters.
 71              A "^" as the first character indicates a complementing set.
 72              #表示一组字符。"^"作为第一个字符表示一组补充。
 73
 74     "|"      A|B, creates an RE that will match either A or B.
 75              #A|B,创建一个将匹配A或B的RE。
 76
 77     (...)    Matches the RE inside the parentheses.
 78              The contents can be retrieved or matched later in the string.
 79              #匹配括号内的RE。稍后可以在字符串中检索或匹配内容。
 80
 81
 82     (?aiLmsux) Set the A, I, L, M, S, U, or X flag for the RE (see below).
 83              #为RE设置A、I、L、M、S、U或X标志(见下面)。
 84
 85     (?:...)  Non-grouping version of regular parentheses.
 86              #非分组版本的规则括号。
 87
 88     (?P<name>...) The substring matched by the group is accessible by name.
 89              #组匹配的子字符串可以通过名称访问。
 90
 91     (?P=name)     Matches the text matched earlier by the group named name.
 92              #匹配前面由名为name的组匹配的文本。
 93
 94     (?#...)  A comment; ignored.
 95     (?=...)  Matches if ... matches next, but doesn't consume the string.
 96              #如果匹配……匹配next,但不使用字符串。
 97
 98     (?!...)  Matches if ... doesn't match next.
 99     (?<=...) Matches if preceded by ... (must be fixed length).
100     (?<!...) Matches if not preceded by ... (must be fixed length).
101     (?(id/name)yes|no) Matches yes pattern if the group with id/name matched,
102                        the (optional) no pattern otherwise.
103                        #如果id/name匹配的组匹配yes模式,(可选)没有其他模式
104
105 The special sequences consist of "\\" and a character from the list
106 below.  If the ordinary character is not on the list, then the
107 resulting RE will match the second character.
108 #特殊的序列由“\\”和列表中的一个字符组成在下面。如果普通字符不在列表中,
109 则结果RE将匹配第二个字符。
110
111     \number  Matches the contents of the group of the same number.
112              #匹配同一数字组的内容。
113
114     \A       Matches only at the start of the string.
115              #只在字符串的开头匹配。
116
117     \Z       Matches only at the end of the string.
118              #只匹配字符串的末尾。
119
120     \b       Matches the empty string, but only at the start or end of a word.
121              #匹配空字符串,但仅在单词的开头或结尾。
122
123     \B       Matches the empty string, but not at the start or end of a word.
124              #匹配空字符串,但不匹配单词的开头或结尾。
125
126     \d       Matches any decimal digit; equivalent to the set [0-9] in
127              bytes patterns or string patterns with the ASCII flag.
128              In string patterns without the ASCII flag, it will match the whole
129              range of Unicode digits.
130              #匹配任何小数;等于集合[0-9]in带有ASCII标志的字节模式或字符串模式。
131              在没有ASCII标志的字符串模式中,它将匹配整个字符串Unicode数字的范围。
132
133     \D       Matches any non-digit character; equivalent to [^\d].
134              #匹配任何非数字字符;相当于^ \ [d]。
135
136     \s       Matches any whitespace character; equivalent to [ \t\n\r\f\v] in
137              bytes patterns or string patterns with the ASCII flag.
138              In string patterns without the ASCII flag, it will match the whole
139              range of Unicode whitespace characters.
140              #匹配任何空白字符;相当于[\t\n\r\f\v] in带有ASCII标志的字节模式或字符串模式。
141              在没有ASCII标志的字符串模式中,它将匹配整个字符串Unicode空白字符的范围。
142
143     \S       Matches any non-whitespace character; equivalent to [^\s].
144              #匹配任何非空白字符;相当于^ \ [s]。
145
146     \w       Matches any alphanumeric character; equivalent to [a-zA-Z0-9_]
147              in bytes patterns or string patterns with the ASCII flag.
148              In string patterns without the ASCII flag, it will match the
149              range of Unicode alphanumeric characters (letters plus digits
150              plus underscore).
151              With LOCALE, it will match the set [0-9_] plus characters defined
152              as letters for the current locale.
153              #匹配任何字母数字字符;
154              [相当于- za - z0 - 9 _]使用ASCII标志的字节模式或字符串模式。
155              在没有ASCII标志的字符串模式中,它将匹配
156              Unicode字母数字字符(字母加数字的范围加上下划线)。
157              对于LOCALE,它将匹配集合[0-9_]和定义的字符作为当前语言环境的字母。
158
159     \W       Matches the complement of \w.
160              #匹配\w的补码。
161
162     \\       Matches a literal backslash.
163              #匹配一个字面反斜杠。
164
165 This module exports the following functions:
166 #本模块导出如下功能:
167
168     match     Match a regular expression pattern to the beginning of a string.
169               #将正则表达式模式匹配到字符串的开头。
170
171     fullmatch Match a regular expression pattern to all of a string.
172               #将正则表达式模式与所有字符串匹配。
173
174     search    Search a string for the presence of a pattern.
175               #在字符串中搜索是否存在模式。
176
177     sub       Substitute occurrences of a pattern found in a string.
178               #替换字符串中出现的模式。
179
180     subn      Same as sub, but also return the number of substitutions made.
181               #与sub相同,但也返回替换次数。
182
183     split     Split a string by the occurrences of a pattern.
184               #通过模式的出现来分割字符串。
185
186     findall   Find all occurrences of a pattern in a string.
187               #查找字符串中出现的所有模式。
188
189     finditer  Return an iterator yielding a Match object for each match.
190               #返回一个迭代器,为每个匹配生成一个匹配对象。
191
192     compile   Compile a pattern into a Pattern object.
193               #将模式编译为模式对象。
194
195     purge     Clear the regular expression cache.
196               #清除正则表达式缓存。
197
198     escape    Backslash all non-alphanumerics in a string.
199               #在字符串中反斜杠所有非字母数字。
200
201 Some of the functions in this module takes flags as optional parameters:
202 #本模块中的一些函数将标志作为可选参数:
203
204     A  ASCII       For string patterns, make \w, \W, \b, \B, \d, \D
205                    match the corresponding ASCII character categories
206                    (rather than the whole Unicode categories, which is the
207                    default).
208                    For bytes patterns, this flag is the only available
209                    behaviour and needn't be specified.
210                    #对于字符串模式,制作\w,\W,\b,\B,\d,\D匹配相应的ASCII字符类别
211                    (而不是整个Unicode类别,也就是违约)。
212                    对于字节模式,这个标志是唯一可用的行为和不需要指定。
213
214     I  IGNORECASE  Perform case-insensitive matching.
215                    #执行不区分大小写的匹配。
216
217     L  LOCALE      Make \w, \W, \b, \B, dependent on the current locale.
218                    #使\w, \W, \b, \B,取决于当前区域设置。
219
220     M  MULTILINE   "^" matches the beginning of lines (after a newline)
221                    as well as the string.
222                    "$" matches the end of lines (before a newline) as well
223                    as the end of the string.
224                    #"^" 匹配的开始行(换行符)还有绳子。
225                    "$" 也匹配行尾(在换行符之前)作为弦的末端。
226
227     S  DOTALL      "." matches any character at all, including the newline.
228                    #"." 匹配任何字符,包括换行符。
229
230     X  VERBOSE     Ignore whitespace and comments for nicer looking RE's.
231                    #为了看起来更漂亮,忽略空白和注释。
232
233     U  UNICODE     For compatibility only. Ignored for string patterns (it
234                    is the default), and forbidden for bytes patterns.
235                    #仅供兼容性。忽略字符串模式(it为默认),并且禁止字节模式。
236
237 This module also defines an exception 'error'.
238
239 """
240
241 import enum
242 import sre_compile
243 import sre_parse
244 import functools
245 try:
246     import _locale
247 except ImportError:
248     _locale = None
249
250
251 # public symbols
252 __all__ = [
253     "match", "fullmatch", "search", "sub", "subn", "split",
254     "findall", "finditer", "compile", "purge", "template", "escape",
255     "error", "Pattern", "Match", "A", "I", "L", "M", "S", "X", "U",
256     "ASCII", "IGNORECASE", "LOCALE", "MULTILINE", "DOTALL", "VERBOSE",
257     "UNICODE",
258 ]
259
260 __version__ = "2.2.1"
261
262 class RegexFlag(enum.IntFlag):
263     ASCII = sre_compile.SRE_FLAG_ASCII # assume ascii "locale"
264     IGNORECASE = sre_compile.SRE_FLAG_IGNORECASE # ignore case
265     LOCALE = sre_compile.SRE_FLAG_LOCALE # assume current 8-bit locale
266     UNICODE = sre_compile.SRE_FLAG_UNICODE # assume unicode "locale"
267     MULTILINE = sre_compile.SRE_FLAG_MULTILINE # make anchors look for newline
268     DOTALL = sre_compile.SRE_FLAG_DOTALL # make dot match newline
269     VERBOSE = sre_compile.SRE_FLAG_VERBOSE # ignore whitespace and comments
270     A = ASCII
271     I = IGNORECASE
272     L = LOCALE
273     U = UNICODE
274     M = MULTILINE
275     S = DOTALL
276     X = VERBOSE
277     # sre extensions (experimental, don't rely on these)
278     TEMPLATE = sre_compile.SRE_FLAG_TEMPLATE # disable backtracking
279     T = TEMPLATE
280     DEBUG = sre_compile.SRE_FLAG_DEBUG # dump pattern after compilation
281 globals().update(RegexFlag.__members__)
282
283 # sre exception
284 error = sre_compile.error
285
286 # --------------------------------------------------------------------
287 # public interface
288
289 def match(pattern, string, flags=0):
290     """Try to apply the pattern at the start of the string, returning
291     a Match object, or None if no match was found."""
292     #尝试在字符串开头应用模式,返回匹配对象,如果没有找到匹配,则返回None。
293     return _compile(pattern, flags).match(string)
294
295 def fullmatch(pattern, string, flags=0):
296     """Try to apply the pattern to all of the string, returning
297     a Match object, or None if no match was found."""
298     #尝试将模式应用于所有字符串,返回匹配对象,或者如果没有找到匹配,返回None。
299     return _compile(pattern, flags).fullmatch(string)
300
301 def search(pattern, string, flags=0):
302     """Scan through string looking for a match to the pattern, returning
303     a Match object, or None if no match was found."""
304     #扫描字符串,查找模式的匹配项,返回匹配对象,如果没有找到匹配项,则返回None。
305     return _compile(pattern, flags).search(string)
306
307 def sub(pattern, repl, string, count=0, flags=0):
308     """Return the string obtained by replacing the leftmost
309     non-overlapping occurrences of the pattern in string by the
310     replacement repl.  repl can be either a string or a callable;
311     if a string, backslash escapes in it are processed.  If it is
312     a callable, it's passed the Match object and must return
313     a replacement string to be used."""
314     #返回通过替换repl替换字符串中最左边不重叠出现的模式而得到的字符串。
315     # repl可以是字符串,也可以是可调用的;如果处理一个字符串,反斜杠转义。
316     # 如果它是可调用的,它将传递Match对象,并且必须返回要使用的替换字符串。
317     return _compile(pattern, flags).sub(repl, string, count)
318
319 def subn(pattern, repl, string, count=0, flags=0):
320     """Return a 2-tuple containing (new_string, number).
321     new_string is the string obtained by replacing the leftmost
322     non-overlapping occurrences of the pattern in the source
323     string by the replacement repl.  number is the number of
324     substitutions that were made. repl can be either a string or a
325     callable; if a string, backslash escapes in it are processed.
326     If it is a callable, it's passed the Match object and must
327     return a replacement string to be used."""
328     #返回一个包含两个元组(new_string, number)。
329     # new_string是通过替换repl替换源字符串中最左边不重叠的模式出现而得到的字符串。
330     # number是替换的次数。repl可以是字符串,也可以是可调用的;
331     # 如果处理一个字符串,反斜杠转义。如果它是可调用的,它将传递Match对象,
332     # 并且必须返回要使用的替换字符串。
333     return _compile(pattern, flags).subn(repl, string, count)
334
335 def split(pattern, string, maxsplit=0, flags=0):
336     """Split the source string by the occurrences of the pattern,
337     returning a list containing the resulting substrings.  If
338     capturing parentheses are used in pattern, then the text of all
339     groups in the pattern are also returned as part of the resulting
340     list.  If maxsplit is nonzero, at most maxsplit splits occur,
341     and the remainder of the string is returned as the final element
342     of the list."""
343     #根据模式的出现情况拆分源字符串,返回一个包含结果子字符串的列表。
344     # 如果模式中使用捕获括号,那么模式中的所有组的文本也会作为结果列表的一部分返回。
345     # 如果maxsplit不为0,那么在大多数情况下会发生maxsplit拆分,
346     # 字符串的其余部分作为列表的最后一个元素返回。
347     return _compile(pattern, flags).split(string, maxsplit)
348
349 def findall(pattern, string, flags=0):
350     """Return a list of all non-overlapping matches in the string.
351
352     If one or more capturing groups are present in the pattern, return
353     a list of groups; this will be a list of tuples if the pattern
354     has more than one group.
355
356     Empty matches are included in the result."""
357     #返回字符串中所有不重叠匹配的列表。
358     # 如果模式中存在一个或多个捕获组,返回组列表;
359     # 如果模式有多个组,那么这将是一个元组列表。
360     # 结果中包含了空匹配。
361     return _compile(pattern, flags).findall(string)
362
363 def finditer(pattern, string, flags=0):
364     """Return an iterator over all non-overlapping matches in the
365     string.  For each match, the iterator returns a Match object.
366
367     Empty matches are included in the result."""
368     #在字符串中所有不重叠的匹配上返回一个迭代器。
369     # 对于每个匹配,迭代器返回一个匹配对象。结果中包含了空匹配。
370     return _compile(pattern, flags).finditer(string)
371
372 def compile(pattern, flags=0):
373     "Compile a regular expression pattern, returning a Pattern object."
374     #编译正则表达式模式,返回模式对象。  用来筛选
375     return _compile(pattern, flags)
376
377 def purge():
378     "Clear the regular expression caches"
379     _cache.clear()
380     _compile_repl.cache_clear()
381
382 def template(pattern, flags=0):
383     "Compile a template pattern, returning a Pattern object"
384     return _compile(pattern, flags|T)
385
386 # SPECIAL_CHARS
387 # closing ')', '}' and ']'
388 # '-' (a range in character set)
389 # '&', '~', (extended character set operations)
390 # '#' (comment) and WHITESPACE (ignored) in verbose mode
391 _special_chars_map = {i: '\\' + chr(i) for i in b'()[]{}?*+-|^$\\.&~# \t\n\r\v\f'}
392
393 def escape(pattern):
394     """
395     Escape special characters in a string.
396     """
397     if isinstance(pattern, str):
398         return pattern.translate(_special_chars_map)
399     else:
400         pattern = str(pattern, 'latin1')
401         return pattern.translate(_special_chars_map).encode('latin1')
402
403 Pattern = type(sre_compile.compile('', 0))
404 Match = type(sre_compile.compile('', 0).match(''))
405
406 # --------------------------------------------------------------------
407 # internals
408
409 _cache = {}  # ordered!
410
411 _MAXCACHE = 512
412 def _compile(pattern, flags):
413     # internal: compile pattern
414     #内部:编译模式
415     if isinstance(flags, RegexFlag):
416         flags = flags.value
417     try:
418         return _cache[type(pattern), pattern, flags]
419     except KeyError:
420         pass
421     if isinstance(pattern, Pattern):
422         if flags:
423             raise ValueError(
424                 "cannot process flags argument with a compiled pattern")
425         return pattern
426     if not sre_compile.isstring(pattern):
427         raise TypeError("first argument must be string or compiled pattern")
428     p = sre_compile.compile(pattern, flags)
429     if not (flags & DEBUG):
430         if len(_cache) >= _MAXCACHE:
431             # Drop the oldest item
432             try:
433                 del _cache[next(iter(_cache))]
434             except (StopIteration, RuntimeError, KeyError):
435                 pass
436         _cache[type(pattern), pattern, flags] = p
437     return p
438
439 @functools.lru_cache(_MAXCACHE)
440 def _compile_repl(repl, pattern):
441     # internal: compile replacement pattern
442     #内部:编译替换模式
443     return sre_parse.parse_template(repl, pattern)
444
445 def _expand(pattern, match, template):
446     # internal: Match.expand implementation hook
447     #内部:匹配。扩大实施钩
448     template = sre_parse.parse_template(template, pattern)
449     return sre_parse.expand_template(template, match)
450
451 def _subx(pattern, template):
452     # internal: Pattern.sub/subn implementation helper
453     #内部:模式。子/ subn实现辅助
454     template = _compile_repl(template, pattern)
455     if not template[0] and len(template[1]) == 1:
456         # literal replacement
457         return template[1][0]
458     def filter(match, template=template):
459         return sre_parse.expand_template(template, match)
460     return filter
461
462 # register myself for pickling
463 #注册为酸洗
464
465 import copyreg
466
467 def _pickle(p):
468     return _compile, (p.pattern, p.flags)
469
470 copyreg.pickle(Pattern, _pickle, _compile)
471
472 # --------------------------------------------------------------------
473 # experimental stuff (see python-dev discussions for details)
474
475 class Scanner:
476     def __init__(self, lexicon, flags=0):
477         from sre_constants import BRANCH, SUBPATTERN
478         if isinstance(flags, RegexFlag):
479             flags = flags.value
480         self.lexicon = lexicon
481         # combine phrases into a compound pattern
482         p = []
483         s = sre_parse.Pattern()
484         s.flags = flags
485         for phrase, action in lexicon:
486             gid = s.opengroup()
487             p.append(sre_parse.SubPattern(s, [
488                 (SUBPATTERN, (gid, 0, 0, sre_parse.parse(phrase, flags))),
489                 ]))
490             s.closegroup(gid, p[-1])
491         p = sre_parse.SubPattern(s, [(BRANCH, (None, p))])
492         self.scanner = sre_compile.compile(p)
493     def scan(self, string):
494         result = []
495         append = result.append
496         match = self.scanner.scanner(string).match
497         i = 0
498         while True:
499             m = match()
500             if not m:
501                 break
502             j = m.end()
503             if i == j:
504                 break
505             action = self.lexicon[m.lastindex-1][1]
506             if callable(action):
507                 self.match = m
508                 action = action(self, m.group())
509             if action is not None:
510                 append(action)
511             i = j
512         return result, string[i:]
re源代码.py

练习:

  • 进度条:
Python   模块-LMLPHPPython   模块-LMLPHP
'''简单进度条1'''
import sys
import time
i = 0
while(True):
    if i<10:
        # print("#",end="") #不加end=时是一列#号,加上之后是一行
        sys.stdout.write("#")  #功能相当于加上end=的print语句
        sys.stdout.flush()     #flush:刷新缓冲区,以0.5s的速度。类似于进度条
        time.sleep(1)
        i+=1
    else:
        break


'''简单进度条2'''
ort sys
import time
l = ["10%","20%","30%","40%","50%","60%","70%","80%","90%","100%"]
for i in range(10):
    sys.stdout.write("\r#")  #\r:返回光标打印之前位置
    sys.stdout.write(l[i])
    sys.stdout.flush()
    time.sleep(0.5)
import sys
'''引发一个异常,如果没有捕获这个异常就会直接退出,
如果捕获到异常就可以做额外工作'''
sys.exit()
View Code
11-20 07:44