Python 标准库概览
操作系统接口
os模块提供了不少与操作系统相关联的函数。
建议使用 "import os" 风格而非 "from os import *"。这样可以保证随操作系统不同而有所变化的 os.open() 不会覆盖内置函数 open()。
在使用 os 这样的大型模块时内置的 dir() 和 help() 函数非常有用:
1 "D:\All Libs\02 DC\Python\Code\StartCoding\venv\Scripts\python.exe" "D:/All Libs/02 DC/Python/Code/StartCoding/标准库概况.py" 2 ['DirEntry', 'F_OK', 'MutableMapping', 'O_APPEND', 'O_BINARY', 'O_CREAT', 'O_EXCL', 'O_NOINHERIT', 'O_RANDOM', 'O_RDONLY', 'O_RDWR', 'O_SEQUENTIAL', 'O_SHORT_LIVED', 'O_TEMPORARY', 'O_TEXT', 'O_TRUNC', 'O_WRONLY', 'P_DETACH', 'P_NOWAIT', 'P_NOWAITO', 'P_OVERLAY', 'P_WAIT', 'PathLike', 'R_OK', 'SEEK_CUR', 'SEEK_END', 'SEEK_SET', 'TMP_MAX', 'W_OK', 'X_OK', '_Environ', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_execvpe', '_exists', '_exit', '_fspath', '_get_exports_list', '_putenv', '_unsetenv', '_wrap_close', 'abc', 'abort', 'access', 'altsep', 'chdir', 'chmod', 'close', 'closerange', 'cpu_count', 'curdir', 'defpath', 'device_encoding', 'devnull', 'dup', 'dup2', 'environ', 'error', 'execl', 'execle', 'execlp', 'execlpe', 'execv', 'execve', 'execvp', 'execvpe', 'extsep', 'fdopen', 'fsdecode', 'fsencode', 'fspath', 'fstat', 'fsync', 'ftruncate', 'get_exec_path', 'get_handle_inheritable', 'get_inheritable', 'get_terminal_size', 'getcwd', 'getcwdb', 'getenv', 'getlogin', 'getpid', 'getppid', 'isatty', 'kill', 'linesep', 'link', 'listdir', 'lseek', 'lstat', 'makedirs', 'mkdir', 'name', 'open', 'pardir', 'path', 'pathsep', 'pipe', 'popen', 'putenv', 'read', 'readlink', 'remove', 'removedirs', 'rename', 'renames', 'replace', 'rmdir', 'scandir', 'sep', 'set_handle_inheritable', 'set_inheritable', 'spawnl', 'spawnle', 'spawnv', 'spawnve', 'st', 'startfile', 'stat', 'stat_result', 'statvfs_result', 'strerror', 'supports_bytes_environ', 'supports_dir_fd', 'supports_effective_ids', 'supports_fd', 'supports_follow_symlinks', 'symlink', 'sys', 'system', 'terminal_size', 'times', 'times_result', 'truncate', 'umask', 'uname_result', 'unlink', 'urandom', 'utime', 'waitpid', 'walk', 'write'] 3 Help on module os: 4 5 NAME 6 os - OS routines for NT or Posix depending on what system we're on. 7 8 DESCRIPTION 9 This exports: 10 - all functions from posix or nt, e.g. unlink, stat, etc. 11 - os.path is either posixpath or ntpath 12 - os.name is either 'posix' or 'nt' 13 - os.curdir is a string representing the current directory (always '.') 14 - os.pardir is a string representing the parent directory (always '..') 15 - os.sep is the (or a most common) pathname separator ('/' or '\\') 16 - os.extsep is the extension separator (always '.') 17 - os.altsep is the alternate pathname separator (None or '/') 18 - os.pathsep is the component separator used in $PATH etc 19 - os.linesep is the line separator in text files ('\r' or '\n' or '\r\n') 20 - os.defpath is the default search path for executables 21 - os.devnull is the file path of the null device ('/dev/null', etc.) 22 23 Programs that import and use 'os' stand a better chance of being 24 portable between different platforms. Of course, they must then 25 only use functions that are defined by all platforms (e.g., unlink 26 and opendir), and leave all pathname manipulation to os.path 27 (e.g., split and join). 28 29 CLASSES 30 builtins.Exception(builtins.BaseException) 31 builtins.OSError 32 builtins.object 33 nt.DirEntry 34 builtins.tuple(builtins.object) 35 nt.times_result 36 nt.uname_result 37 stat_result 38 statvfs_result 39 terminal_size 40 41 class DirEntry(builtins.object) 42 | Methods defined here: 43 | 44 | __fspath__(self, /) 45 | Returns the path for the entry. 46 | 47 | __repr__(self, /) 48 | Return repr(self). 49 | 50 | inode(self, /) 51 | Return inode of the entry; cached per entry. 52 | 53 | is_dir(self, /, *, follow_symlinks=True) 54 | Return True if the entry is a directory; cached per entry. 55 | 56 | is_file(self, /, *, follow_symlinks=True) 57 | Return True if the entry is a file; cached per entry. 58 | 59 | is_symlink(self, /) 60 | Return True if the entry is a symbolic link; cached per entry. 61 | 62 | stat(self, /, *, follow_symlinks=True) 63 | Return stat_result object for the entry; cached per entry. 64 | 65 | ---------------------------------------------------------------------- 66 | Data descriptors defined here: 67 | 68 | name 69 | the entry's base filename, relative to scandir() "path" argument 70 | 71 | path 72 | the entry's full path name; equivalent to os.path.join(scandir_path, entry.name) 73 74 error = class OSError(Exception) 75 | Base class for I/O related errors. 76 | 77 | Method resolution order: 78 | OSError 79 | Exception 80 | BaseException 81 | object 82 | 83 | Methods defined here: 84 | 85 | __init__(self, /, *args, **kwargs) 86 | Initialize self. See help(type(self)) for accurate signature. 87 | 88 | __reduce__(...) 89 | Helper for pickle. 90 | 91 | __str__(self, /) 92 | Return str(self). 93 | 94 | ---------------------------------------------------------------------- 95 | Static methods defined here: 96 | 97 | __new__(*args, **kwargs) from builtins.type 98 | Create and return a new object. See help(type) for accurate signature. 99 | 100 | ---------------------------------------------------------------------- 101 | Data descriptors defined here: 102 | 103 | characters_written 104 | 105 | errno 106 | POSIX exception code 107 | 108 | filename 109 | exception filename 110 | 111 | filename2 112 | second exception filename 113 | 114 | strerror 115 | exception strerror 116 | 117 | winerror 118 | Win32 exception code 119 | 120 | ---------------------------------------------------------------------- 121 | Methods inherited from BaseException: 122 | 123 | __delattr__(self, name, /) 124 | Implement delattr(self, name). 125 | 126 | __getattribute__(self, name, /) 127 | Return getattr(self, name). 128 | 129 | __repr__(self, /) 130 | Return repr(self). 131 | 132 | __setattr__(self, name, value, /) 133 | Implement setattr(self, name, value). 134 | 135 | __setstate__(...) 136 | 137 | with_traceback(...) 138 | Exception.with_traceback(tb) -- 139 | set self.__traceback__ to tb and return self. 140 | 141 | ---------------------------------------------------------------------- 142 | Data descriptors inherited from BaseException: 143 | 144 | __cause__ 145 | exception cause 146 | 147 | __context__ 148 | exception context 149 | 150 | __dict__ 151 | 152 | __suppress_context__ 153 | 154 | __traceback__ 155 | 156 | args 157 158 class stat_result(builtins.tuple) 159 | stat_result(iterable=(), /) 160 | 161 | stat_result: Result from stat, fstat, or lstat. 162 | 163 | This object may be accessed either as a tuple of 164 | (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime) 165 | or via the attributes st_mode, st_ino, st_dev, st_nlink, st_uid, and so on. 166 | 167 | Posix/windows: If your platform supports st_blksize, st_blocks, st_rdev, 168 | or st_flags, they are available as attributes only. 169 | 170 | See os.stat for more information. 171 | 172 | Method resolution order: 173 | stat_result 174 | builtins.tuple 175 | builtins.object 176 | 177 | Methods defined here: 178 | 179 | __reduce__(...) 180 | Helper for pickle. 181 | 182 | __repr__(self, /) 183 | Return repr(self). 184 | 185 | ---------------------------------------------------------------------- 186 | Static methods defined here: 187 | 188 | __new__(*args, **kwargs) from builtins.type 189 | Create and return a new object. See help(type) for accurate signature. 190 | 191 | ---------------------------------------------------------------------- 192 | Data descriptors defined here: 193 | 194 | st_atime 195 | time of last access 196 | 197 | st_atime_ns 198 | time of last access in nanoseconds 199 | 200 | st_ctime 201 | time of last change 202 | 203 | st_ctime_ns 204 | time of last change in nanoseconds 205 | 206 | st_dev 207 | device 208 | 209 | st_file_attributes 210 | Windows file attribute bits 211 | 212 | st_gid 213 | group ID of owner 214 | 215 | st_ino 216 | inode 217 | 218 | st_mode 219 | protection bits 220 | 221 | st_mtime 222 | time of last modification 223 | 224 | st_mtime_ns 225 | time of last modification in nanoseconds 226 | 227 | st_nlink 228 | number of hard links 229 | 230 | st_size 231 | total size, in bytes 232 | 233 | st_uid 234 | user ID of owner 235 | 236 | ---------------------------------------------------------------------- 237 | Data and other attributes defined here: 238 | 239 | n_fields = 17 240 | 241 | n_sequence_fields = 10 242 | 243 | n_unnamed_fields = 3 244 | 245 | ---------------------------------------------------------------------- 246 | Methods inherited from builtins.tuple: 247 | 248 | __add__(self, value, /) 249 | Return self+value. 250 | 251 | __contains__(self, key, /) 252 | Return key in self. 253 | 254 | __eq__(self, value, /) 255 | Return self==value. 256 | 257 | __ge__(self, value, /) 258 | Return self>=value. 259 | 260 | __getattribute__(self, name, /) 261 | Return getattr(self, name). 262 | 263 | __getitem__(self, key, /) 264 | Return self[key]. 265 | 266 | __getnewargs__(self, /) 267 | 268 | __gt__(self, value, /) 269 | Return self>value. 270 | 271 | __hash__(self, /) 272 | Return hash(self). 273 | 274 | __iter__(self, /) 275 | Implement iter(self). 276 | 277 | __le__(self, value, /) 278 | Return self<=value. 279 | 280 | __len__(self, /) 281 | Return len(self). 282 | 283 | __lt__(self, value, /) 284 | Return self<value. 285 | 286 | __mul__(self, value, /) 287 | Return self*value. 288 | 289 | __ne__(self, value, /) 290 | Return self!=value. 291 | 292 | __rmul__(self, value, /) 293 | Return value*self. 294 | 295 | count(self, value, /) 296 | Return number of occurrences of value. 297 | 298 | index(self, value, start=0, stop=2147483647, /) 299 | Return first index of value. 300 | 301 | Raises ValueError if the value is not present. 302 303 class statvfs_result(builtins.tuple) 304 | statvfs_result(iterable=(), /) 305 | 306 | statvfs_result: Result from statvfs or fstatvfs. 307 | 308 | This object may be accessed either as a tuple of 309 | (bsize, frsize, blocks, bfree, bavail, files, ffree, favail, flag, namemax), 310 | or via the attributes f_bsize, f_frsize, f_blocks, f_bfree, and so on. 311 | 312 | See os.statvfs for more information. 313 | 314 | Method resolution order: 315 | statvfs_result 316 | builtins.tuple 317 | builtins.object 318 | 319 | Methods defined here: 320 | 321 | __reduce__(...) 322 | Helper for pickle. 323 | 324 | __repr__(self, /) 325 | Return repr(self). 326 | 327 | ---------------------------------------------------------------------- 328 | Static methods defined here: 329 | 330 | __new__(*args, **kwargs) from builtins.type 331 | Create and return a new object. See help(type) for accurate signature. 332 | 333 | ---------------------------------------------------------------------- 334 | Data descriptors defined here: 335 | 336 | f_bavail 337 | 338 | f_bfree 339 | 340 | f_blocks 341 | 342 | f_bsize 343 | 344 | f_favail 345 | 346 | f_ffree 347 | 348 | f_files 349 | 350 | f_flag 351 | 352 | f_frsize 353 | 354 | f_fsid 355 | 356 | f_namemax 357 | 358 | ---------------------------------------------------------------------- 359 | Data and other attributes defined here: 360 | 361 | n_fields = 11 362 | 363 | n_sequence_fields = 10 364 | 365 | n_unnamed_fields = 0 366 | 367 | ---------------------------------------------------------------------- 368 | Methods inherited from builtins.tuple: 369 | 370 | __add__(self, value, /) 371 | Return self+value. 372 | 373 | __contains__(self, key, /) 374 | Return key in self. 375 | 376 | __eq__(self, value, /) 377 | Return self==value. 378 | 379 | __ge__(self, value, /) 380 | Return self>=value. 381 | 382 | __getattribute__(self, name, /) 383 | Return getattr(self, name). 384 | 385 | __getitem__(self, key, /) 386 | Return self[key]. 387 | 388 | __getnewargs__(self, /) 389 | 390 | __gt__(self, value, /) 391 | Return self>value. 392 | 393 | __hash__(self, /) 394 | Return hash(self). 395 | 396 | __iter__(self, /) 397 | Implement iter(self). 398 | 399 | __le__(self, value, /) 400 | Return self<=value. 401 | 402 | __len__(self, /) 403 | Return len(self). 404 | 405 | __lt__(self, value, /) 406 | Return self<value. 407 | 408 | __mul__(self, value, /) 409 | Return self*value. 410 | 411 | __ne__(self, value, /) 412 | Return self!=value. 413 | 414 | __rmul__(self, value, /) 415 | Return value*self. 416 | 417 | count(self, value, /) 418 | Return number of occurrences of value. 419 | 420 | index(self, value, start=0, stop=2147483647, /) 421 | Return first index of value. 422 | 423 | Raises ValueError if the value is not present. 424 425 class terminal_size(builtins.tuple) 426 | terminal_size(iterable=(), /) 427 | 428 | A tuple of (columns, lines) for holding terminal window size 429 | 430 | Method resolution order: 431 | terminal_size 432 | builtins.tuple 433 | builtins.object 434 | 435 | Methods defined here: 436 | 437 | __reduce__(...) 438 | Helper for pickle. 439 | 440 | __repr__(self, /) 441 | Return repr(self). 442 | 443 | ---------------------------------------------------------------------- 444 | Static methods defined here: 445 | 446 | __new__(*args, **kwargs) from builtins.type 447 | Create and return a new object. See help(type) for accurate signature. 448 | 449 | ---------------------------------------------------------------------- 450 | Data descriptors defined here: 451 | 452 | columns 453 | width of the terminal window in characters 454 | 455 | lines 456 | height of the terminal window in characters 457 | 458 | ---------------------------------------------------------------------- 459 | Data and other attributes defined here: 460 | 461 | n_fields = 2 462 | 463 | n_sequence_fields = 2 464 | 465 | n_unnamed_fields = 0 466 | 467 | ---------------------------------------------------------------------- 468 | Methods inherited from builtins.tuple: 469 | 470 | __add__(self, value, /) 471 | Return self+value. 472 | 473 | __contains__(self, key, /) 474 | Return key in self. 475 | 476 | __eq__(self, value, /) 477 | Return self==value. 478 | 479 | __ge__(self, value, /) 480 | Return self>=value. 481 | 482 | __getattribute__(self, name, /) 483 | Return getattr(self, name). 484 | 485 | __getitem__(self, key, /) 486 | Return self[key]. 487 | 488 | __getnewargs__(self, /) 489 | 490 | __gt__(self, value, /) 491 | Return self>value. 492 | 493 | __hash__(self, /) 494 | Return hash(self). 495 | 496 | __iter__(self, /) 497 | Implement iter(self). 498 | 499 | __le__(self, value, /) 500 | Return self<=value. 501 | 502 | __len__(self, /) 503 | Return len(self). 504 | 505 | __lt__(self, value, /) 506 | Return self<value. 507 | 508 | __mul__(self, value, /) 509 | Return self*value. 510 | 511 | __ne__(self, value, /) 512 | Return self!=value. 513 | 514 | __rmul__(self, value, /) 515 | Return value*self. 516 | 517 | count(self, value, /) 518 | Return number of occurrences of value. 519 | 520 | index(self, value, start=0, stop=2147483647, /) 521 | Return first index of value. 522 | 523 | Raises ValueError if the value is not present. 524 525 class times_result(builtins.tuple) 526 | times_result(iterable=(), /) 527 | 528 | times_result: Result from os.times(). 529 | 530 | This object may be accessed either as a tuple of 531 | (user, system, children_user, children_system, elapsed), 532 | or via the attributes user, system, children_user, children_system, 533 | and elapsed. 534 | 535 | See os.times for more information. 536 | 537 | Method resolution order: 538 | times_result 539 | builtins.tuple 540 | builtins.object 541 | 542 | Methods defined here: 543 | 544 | __reduce__(...) 545 | Helper for pickle. 546 | 547 | __repr__(self, /) 548 | Return repr(self). 549 | 550 | ---------------------------------------------------------------------- 551 | Static methods defined here: 552 | 553 | __new__(*args, **kwargs) from builtins.type 554 | Create and return a new object. See help(type) for accurate signature. 555 | 556 | ---------------------------------------------------------------------- 557 | Data descriptors defined here: 558 | 559 | children_system 560 | system time of children 561 | 562 | children_user 563 | user time of children 564 | 565 | elapsed 566 | elapsed time since an arbitrary point in the past 567 | 568 | system 569 | system time 570 | 571 | user 572 | user time 573 | 574 | ---------------------------------------------------------------------- 575 | Data and other attributes defined here: 576 | 577 | n_fields = 5 578 | 579 | n_sequence_fields = 5 580 | 581 | n_unnamed_fields = 0 582 | 583 | ---------------------------------------------------------------------- 584 | Methods inherited from builtins.tuple: 585 | 586 | __add__(self, value, /) 587 | Return self+value. 588 | 589 | __contains__(self, key, /) 590 | Return key in self. 591 | 592 | __eq__(self, value, /) 593 | Return self==value. 594 | 595 | __ge__(self, value, /) 596 | Return self>=value. 597 | 598 | __getattribute__(self, name, /) 599 | Return getattr(self, name). 600 | 601 | __getitem__(self, key, /) 602 | Return self[key]. 603 | 604 | __getnewargs__(self, /) 605 | 606 | __gt__(self, value, /) 607 | Return self>value. 608 | 609 | __hash__(self, /) 610 | Return hash(self). 611 | 612 | __iter__(self, /) 613 | Implement iter(self). 614 | 615 | __le__(self, value, /) 616 | Return self<=value. 617 | 618 | __len__(self, /) 619 | Return len(self). 620 | 621 | __lt__(self, value, /) 622 | Return self<value. 623 | 624 | __mul__(self, value, /) 625 | Return self*value. 626 | 627 | __ne__(self, value, /) 628 | Return self!=value. 629 | 630 | __rmul__(self, value, /) 631 | Return value*self. 632 | 633 | count(self, value, /) 634 | Return number of occurrences of value. 635 | 636 | index(self, value, start=0, stop=2147483647, /) 637 | Return first index of value. 638 | 639 | Raises ValueError if the value is not present. 640 641 class uname_result(builtins.tuple) 642 | uname_result(iterable=(), /) 643 | 644 | uname_result: Result from os.uname(). 645 | 646 | This object may be accessed either as a tuple of 647 | (sysname, nodename, release, version, machine), 648 | or via the attributes sysname, nodename, release, version, and machine. 649 | 650 | See os.uname for more information. 651 | 652 | Method resolution order: 653 | uname_result 654 | builtins.tuple 655 | builtins.object 656 | 657 | Methods defined here: 658 | 659 | __reduce__(...) 660 | Helper for pickle. 661 | 662 | __repr__(self, /) 663 | Return repr(self). 664 | 665 | ---------------------------------------------------------------------- 666 | Static methods defined here: 667 | 668 | __new__(*args, **kwargs) from builtins.type 669 | Create and return a new object. See help(type) for accurate signature. 670 | 671 | ---------------------------------------------------------------------- 672 | Data descriptors defined here: 673 | 674 | machine 675 | hardware identifier 676 | 677 | nodename 678 | name of machine on network (implementation-defined) 679 | 680 | release 681 | operating system release 682 | 683 | sysname 684 | operating system name 685 | 686 | version 687 | operating system version 688 | 689 | ---------------------------------------------------------------------- 690 | Data and other attributes defined here: 691 | 692 | n_fields = 5 693 | 694 | n_sequence_fields = 5 695 | 696 | n_unnamed_fields = 0 697 | 698 | ---------------------------------------------------------------------- 699 | Methods inherited from builtins.tuple: 700 | 701 | __add__(self, value, /) 702 | Return self+value. 703 | 704 | __contains__(self, key, /) 705 | Return key in self. 706 | 707 | __eq__(self, value, /) 708 | Return self==value. 709 | 710 | __ge__(self, value, /) 711 | Return self>=value. 712 | 713 | __getattribute__(self, name, /) 714 | Return getattr(self, name). 715 | 716 | __getitem__(self, key, /) 717 | Return self[key]. 718 | 719 | __getnewargs__(self, /) 720 | 721 | __gt__(self, value, /) 722 | Return self>value. 723 | 724 | __hash__(self, /) 725 | Return hash(self). 726 | 727 | __iter__(self, /) 728 | Implement iter(self). 729 | 730 | __le__(self, value, /) 731 | Return self<=value. 732 | 733 | __len__(self, /) 734 | Return len(self). 735 | 736 | __lt__(self, value, /) 737 | Return self<value. 738 | 739 | __mul__(self, value, /) 740 | Return self*value. 741 | 742 | __ne__(self, value, /) 743 | Return self!=value. 744 | 745 | __rmul__(self, value, /) 746 | Return value*self. 747 | 748 | count(self, value, /) 749 | Return number of occurrences of value. 750 | 751 | index(self, value, start=0, stop=2147483647, /) 752 | Return first index of value. 753 | 754 | Raises ValueError if the value is not present. 755 756 FUNCTIONS 757 _exit(status) 758 Exit to the system with specified status, without normal exit processing. 759 760 abort() 761 Abort the interpreter immediately. 762 763 This function 'dumps core' or otherwise fails in the hardest way possible 764 on the hosting operating system. This function never returns. 765 766 access(path, mode, *, dir_fd=None, effective_ids=False, follow_symlinks=True) 767 Use the real uid/gid to test for access to a path. 768 769 path 770 Path to be tested; can be string, bytes, or a path-like object. 771 mode 772 Operating-system mode bitfield. Can be F_OK to test existence, 773 or the inclusive-OR of R_OK, W_OK, and X_OK. 774 dir_fd 775 If not None, it should be a file descriptor open to a directory, 776 and path should be relative; path will then be relative to that 777 directory. 778 effective_ids 779 If True, access will use the effective uid/gid instead of 780 the real uid/gid. 781 follow_symlinks 782 If False, and the last element of the path is a symbolic link, 783 access will examine the symbolic link itself instead of the file 784 the link points to. 785 786 dir_fd, effective_ids, and follow_symlinks may not be implemented 787 on your platform. If they are unavailable, using them will raise a 788 NotImplementedError. 789 790 Note that most operations will use the effective uid/gid, therefore this 791 routine can be used in a suid/sgid environment to test if the invoking user 792 has the specified access to the path. 793 794 chdir(path) 795 Change the current working directory to the specified path. 796 797 path may always be specified as a string. 798 On some platforms, path may also be specified as an open file descriptor. 799 If this functionality is unavailable, using it raises an exception. 800 801 chmod(path, mode, *, dir_fd=None, follow_symlinks=True) 802 Change the access permissions of a file. 803 804 path 805 Path to be modified. May always be specified as a str, bytes, or a path-like object. 806 On some platforms, path may also be specified as an open file descriptor. 807 If this functionality is unavailable, using it raises an exception. 808 mode 809 Operating-system mode bitfield. 810 dir_fd 811 If not None, it should be a file descriptor open to a directory, 812 and path should be relative; path will then be relative to that 813 directory. 814 follow_symlinks 815 If False, and the last element of the path is a symbolic link, 816 chmod will modify the symbolic link itself instead of the file 817 the link points to. 818 819 It is an error to use dir_fd or follow_symlinks when specifying path as 820 an open file descriptor. 821 dir_fd and follow_symlinks may not be implemented on your platform. 822 If they are unavailable, using them will raise a NotImplementedError. 823 824 close(fd) 825 Close a file descriptor. 826 827 closerange(fd_low, fd_high, /) 828 Closes all file descriptors in [fd_low, fd_high), ignoring errors. 829 830 cpu_count() 831 Return the number of CPUs in the system; return None if indeterminable. 832 833 This number is not equivalent to the number of CPUs the current process can 834 use. The number of usable CPUs can be obtained with 835 ``len(os.sched_getaffinity(0))`` 836 837 device_encoding(fd) 838 Return a string describing the encoding of a terminal's file descriptor. 839 840 The file descriptor must be attached to a terminal. 841 If the device is not a terminal, return None. 842 843 dup(fd, /) 844 Return a duplicate of a file descriptor. 845 846 dup2(fd, fd2, inheritable=True) 847 Duplicate file descriptor. 848 849 execl(file, *args) 850 execl(file, *args) 851 852 Execute the executable file with argument list args, replacing the 853 current process. 854 855 execle(file, *args) 856 execle(file, *args, env) 857 858 Execute the executable file with argument list args and 859 environment env, replacing the current process. 860 861 execlp(file, *args) 862 execlp(file, *args) 863 864 Execute the executable file (which is searched for along $PATH) 865 with argument list args, replacing the current process. 866 867 execlpe(file, *args) 868 execlpe(file, *args, env) 869 870 Execute the executable file (which is searched for along $PATH) 871 with argument list args and environment env, replacing the current 872 process. 873 874 execv(path, argv, /) 875 Execute an executable path with arguments, replacing current process. 876 877 path 878 Path of executable file. 879 argv 880 Tuple or list of strings. 881 882 execve(path, argv, env) 883 Execute an executable path with arguments, replacing current process. 884 885 path 886 Path of executable file. 887 argv 888 Tuple or list of strings. 889 env 890 Dictionary of strings mapping to strings. 891 892 execvp(file, args) 893 execvp(file, args) 894 895 Execute the executable file (which is searched for along $PATH) 896 with argument list args, replacing the current process. 897 args may be a list or tuple of strings. 898 899 execvpe(file, args, env) 900 execvpe(file, args, env) 901 902 Execute the executable file (which is searched for along $PATH) 903 with argument list args and environment env , replacing the 904 current process. 905 args may be a list or tuple of strings. 906 907 fdopen(fd, *args, **kwargs) 908 # Supply os.fdopen() 909 910 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 fsencode(filename) 917 Encode filename (an os.PathLike, bytes, or str) to the filesystem 918 encoding with 'surrogateescape' error handler, return bytes unchanged. 919 On Windows, use 'strict' error handler if the file system encoding is 920 'mbcs' (which is the default encoding). 921 922 fspath(path) 923 Return the file system path representation of the object. 924 925 If the object is str or bytes, then allow it to pass through as-is. If the 926 object defines __fspath__(), then return the result of that method. All other 927 types raise a TypeError. 928 929 fstat(fd) 930 Perform a stat system call on the given file descriptor. 931 932 Like stat(), but for an open file descriptor. 933 Equivalent to os.stat(fd). 934 935 fsync(fd) 936 Force write of fd to disk. 937 938 ftruncate(fd, length, /) 939 Truncate a file, specified by file descriptor, to a specific length. 940 941 get_exec_path(env=None) 942 Returns the sequence of directories that will be searched for the 943 named executable (similar to a shell) when launching a process. 944 945 *env* must be an environment variable dict or None. If *env* is None, 946 os.environ will be used. 947 948 get_handle_inheritable(handle, /) 949 Get the close-on-exe flag of the specified file descriptor. 950 951 get_inheritable(fd, /) 952 Get the close-on-exe flag of the specified file descriptor. 953 954 get_terminal_size(...) 955 Return the size of the terminal window as (columns, lines). 956 957 The optional argument fd (default standard output) specifies 958 which file descriptor should be queried. 959 960 If the file descriptor is not connected to a terminal, an OSError 961 is thrown. 962 963 This function will only be defined if an implementation is 964 available for this system. 965 966 shutil.get_terminal_size is the high-level function which should 967 normally be used, os.get_terminal_size is the low-level implementation. 968 969 getcwd() 970 Return a unicode string representing the current working directory. 971 972 getcwdb() 973 Return a bytes string representing the current working directory. 974 975 getenv(key, default=None) 976 Get an environment variable, return None if it doesn't exist. 977 The optional second argument can specify an alternate default. 978 key, default and the result are str. 979 980 getlogin() 981 Return the actual login name. 982 983 getpid() 984 Return the current process id. 985 986 getppid() 987 Return the parent's process id. 988 989 If the parent process has already exited, Windows machines will still 990 return its id; others systems will return the id of the 'init' process (1). 991 992 isatty(fd, /) 993 Return True if the fd is connected to a terminal. 994 995 Return True if the file descriptor is an open file descriptor 996 connected to the slave end of a terminal. 997 998 kill(pid, signal, /) 999 Kill a process with a signal. 1000 1001 link(src, dst, *, src_dir_fd=None, dst_dir_fd=None, follow_symlinks=True) 1002 Create a hard link to a file. 1003 1004 If either src_dir_fd or dst_dir_fd is not None, it should be a file 1005 descriptor open to a directory, and the respective path string (src or dst) 1006 should be relative; the path will then be relative to that directory. 1007 If follow_symlinks is False, and the last element of src is a symbolic 1008 link, link will create a link to the symbolic link itself instead of the 1009 file the link points to. 1010 src_dir_fd, dst_dir_fd, and follow_symlinks may not be implemented on your 1011 platform. If they are unavailable, using them will raise a 1012 NotImplementedError. 1013 1014 listdir(path=None) 1015 Return a list containing the names of the files in the directory. 1016 1017 path can be specified as either str, bytes, or a path-like object. If path is bytes, 1018 the filenames returned will also be bytes; in all other circumstances 1019 the filenames returned will be str. 1020 If path is None, uses the path='.'. 1021 On some platforms, path may also be specified as an open file descriptor;\ 1022 the file descriptor must refer to a directory. 1023 If this functionality is unavailable, using it raises NotImplementedError. 1024 1025 The list is in arbitrary order. It does not include the special 1026 entries '.' and '..' even if they are present in the directory. 1027 1028 lseek(fd, position, how, /) 1029 Set the position of a file descriptor. Return the new position. 1030 1031 Return the new cursor position in number of bytes 1032 relative to the beginning of the file. 1033 1034 lstat(path, *, dir_fd=None) 1035 Perform a stat system call on the given path, without following symbolic links. 1036 1037 Like stat(), but do not follow symbolic links. 1038 Equivalent to stat(path, follow_symlinks=False). 1039 1040 makedirs(name, mode=511, exist_ok=False) 1041 makedirs(name [, mode=0o777][, exist_ok=False]) 1042 1043 Super-mkdir; create a leaf directory and all intermediate ones. Works like 1044 mkdir, except that any intermediate path segment (not just the rightmost) 1045 will be created if it does not exist. If the target directory already 1046 exists, raise an OSError if exist_ok is False. Otherwise no exception is 1047 raised. This is recursive. 1048 1049 mkdir(path, mode=511, *, dir_fd=None) 1050 Create a directory. 1051 1052 If dir_fd is not None, it should be a file descriptor open to a directory, 1053 and path should be relative; path will then be relative to that directory. 1054 dir_fd may not be implemented on your platform. 1055 If it is unavailable, using it will raise a NotImplementedError. 1056 1057 The mode argument is ignored on Windows. 1058 1059 open(path, flags, mode=511, *, dir_fd=None) 1060 Open a file for low level IO. Returns a file descriptor (integer). 1061 1062 If dir_fd is not None, it should be a file descriptor open to a directory, 1063 and path should be relative; path will then be relative to that directory. 1064 dir_fd may not be implemented on your platform. 1065 If it is unavailable, using it will raise a NotImplementedError. 1066 1067 pipe() 1068 Create a pipe. 1069 1070 Returns a tuple of two file descriptors: 1071 (read_fd, write_fd) 1072 1073 popen(cmd, mode='r', buffering=-1) 1074 # Supply os.popen() 1075 1076 putenv(name, value, /) 1077 Change or add an environment variable. 1078 1079 read(fd, length, /) 1080 Read from a file descriptor. Returns a bytes object. 1081 1082 readlink(...) 1083 readlink(path, *, dir_fd=None) -> path 1084 1085 Return a string representing the path to which the symbolic link points. 1086 1087 If dir_fd is not None, it should be a file descriptor open to a directory, 1088 and path should be relative; path will then be relative to that directory. 1089 dir_fd may not be implemented on your platform. 1090 If it is unavailable, using it will raise a NotImplementedError. 1091 1092 remove(path, *, dir_fd=None) 1093 Remove a file (same as unlink()). 1094 1095 If dir_fd is not None, it should be a file descriptor open to a directory, 1096 and path should be relative; path will then be relative to that directory. 1097 dir_fd may not be implemented on your platform. 1098 If it is unavailable, using it will raise a NotImplementedError. 1099 1100 removedirs(name) 1101 removedirs(name) 1102 1103 Super-rmdir; remove a leaf directory and all empty intermediate 1104 ones. Works like rmdir except that, if the leaf directory is 1105 successfully removed, directories corresponding to rightmost path 1106 segments will be pruned away until either the whole path is 1107 consumed or an error occurs. Errors during this latter phase are 1108 ignored -- they generally mean that a directory was not empty. 1109 1110 rename(src, dst, *, src_dir_fd=None, dst_dir_fd=None) 1111 Rename a file or directory. 1112 1113 If either src_dir_fd or dst_dir_fd is not None, it should be a file 1114 descriptor open to a directory, and the respective path string (src or dst) 1115 should be relative; the path will then be relative to that directory. 1116 src_dir_fd and dst_dir_fd, may not be implemented on your platform. 1117 If they are unavailable, using them will raise a NotImplementedError. 1118 1119 renames(old, new) 1120 renames(old, new) 1121 1122 Super-rename; create directories as necessary and delete any left 1123 empty. Works like rename, except creation of any intermediate 1124 directories needed to make the new pathname good is attempted 1125 first. After the rename, directories corresponding to rightmost 1126 path segments of the old name will be pruned until either the 1127 whole path is consumed or a nonempty directory is found. 1128 1129 Note: this function can fail with the new directory structure made 1130 if you lack permissions needed to unlink the leaf directory or 1131 file. 1132 1133 replace(src, dst, *, src_dir_fd=None, dst_dir_fd=None) 1134 Rename a file or directory, overwriting the destination. 1135 1136 If either src_dir_fd or dst_dir_fd is not None, it should be a file 1137 descriptor open to a directory, and the respective path string (src or dst) 1138 should be relative; the path will then be relative to that directory. 1139 src_dir_fd and dst_dir_fd, may not be implemented on your platform. 1140 If they are unavailable, using them will raise a NotImplementedError. 1141 1142 rmdir(path, *, dir_fd=None) 1143 Remove a directory. 1144 1145 If dir_fd is not None, it should be a file descriptor open to a directory, 1146 and path should be relative; path will then be relative to that directory. 1147 dir_fd may not be implemented on your platform. 1148 If it is unavailable, using it will raise a NotImplementedError. 1149 1150 scandir(path=None) 1151 Return an iterator of DirEntry objects for given path. 1152 1153 path can be specified as either str, bytes, or a path-like object. If path 1154 is bytes, the names of yielded DirEntry objects will also be bytes; in 1155 all other circumstances they will be str. 1156 1157 If path is None, uses the path='.'. 1158 1159 set_handle_inheritable(handle, inheritable, /) 1160 Set the inheritable flag of the specified handle. 1161 1162 set_inheritable(fd, inheritable, /) 1163 Set the inheritable flag of the specified file descriptor. 1164 1165 spawnl(mode, file, *args) 1166 spawnl(mode, file, *args) -> integer 1167 1168 Execute file with arguments from args in a subprocess. 1169 If mode == P_NOWAIT return the pid of the process. 1170 If mode == P_WAIT return the process's exit code if it exits normally; 1171 otherwise return -SIG, where SIG is the signal that killed it. 1172 1173 spawnle(mode, file, *args) 1174 spawnle(mode, file, *args, env) -> integer 1175 1176 Execute file with arguments from args in a subprocess with the 1177 supplied environment. 1178 If mode == P_NOWAIT return the pid of the process. 1179 If mode == P_WAIT return the process's exit code if it exits normally; 1180 otherwise return -SIG, where SIG is the signal that killed it. 1181 1182 spawnv(mode, path, argv, /) 1183 Execute the program specified by path in a new process. 1184 1185 mode 1186 Mode of process creation. 1187 path 1188 Path of executable file. 1189 argv 1190 Tuple or list of strings. 1191 1192 spawnve(mode, path, argv, env, /) 1193 Execute the program specified by path in a new process. 1194 1195 mode 1196 Mode of process creation. 1197 path 1198 Path of executable file. 1199 argv 1200 Tuple or list of strings. 1201 env 1202 Dictionary of strings mapping to strings. 1203 1204 startfile(filepath, operation=None) 1205 startfile(filepath [, operation]) 1206 1207 Start a file with its associated application. 1208 1209 When "operation" is not specified or "open", this acts like 1210 double-clicking the file in Explorer, or giving the file name as an 1211 argument to the DOS "start" command: the file is opened with whatever 1212 application (if any) its extension is associated. 1213 When another "operation" is given, it specifies what should be done with 1214 the file. A typical operation is "print". 1215 1216 startfile returns as soon as the associated application is launched. 1217 There is no option to wait for the application to close, and no way 1218 to retrieve the application's exit status. 1219 1220 The filepath is relative to the current directory. If you want to use 1221 an absolute path, make sure the first character is not a slash ("/"); 1222 the underlying Win32 ShellExecute function doesn't work if it is. 1223 1224 stat(path, *, dir_fd=None, follow_symlinks=True) 1225 Perform a stat system call on the given path. 1226 1227 path 1228 Path to be examined; can be string, bytes, a path-like object or 1229 open-file-descriptor int. 1230 dir_fd 1231 If not None, it should be a file descriptor open to a directory, 1232 and path should be a relative string; path will then be relative to 1233 that directory. 1234 follow_symlinks 1235 If False, and the last element of the path is a symbolic link, 1236 stat will examine the symbolic link itself instead of the file 1237 the link points to. 1238 1239 dir_fd and follow_symlinks may not be implemented 1240 on your platform. If they are unavailable, using them will raise a 1241 NotImplementedError. 1242 1243 It's an error to use dir_fd or follow_symlinks when specifying path as 1244 an open file descriptor. 1245 1246 strerror(code, /) 1247 Translate an error code to a message string. 1248 1249 symlink(src, dst, target_is_directory=False, *, dir_fd=None) 1250 Create a symbolic link pointing to src named dst. 1251 1252 target_is_directory is required on Windows if the target is to be 1253 interpreted as a directory. (On Windows, symlink requires 1254 Windows 6.0 or greater, and raises a NotImplementedError otherwise.) 1255 target_is_directory is ignored on non-Windows platforms. 1256 1257 If dir_fd is not None, it should be a file descriptor open to a directory, 1258 and path should be relative; path will then be relative to that directory. 1259 dir_fd may not be implemented on your platform. 1260 If it is unavailable, using it will raise a NotImplementedError. 1261 1262 system(command) 1263 Execute the command in a subshell. 1264 1265 times() 1266 Return a collection containing process timing information. 1267 1268 The object returned behaves like a named tuple with these fields: 1269 (utime, stime, cutime, cstime, elapsed_time) 1270 All fields are floating point numbers. 1271 1272 truncate(path, length) 1273 Truncate a file, specified by path, to a specific length. 1274 1275 On some platforms, path may also be specified as an open file descriptor. 1276 If this functionality is unavailable, using it raises an exception. 1277 1278 umask(mask, /) 1279 Set the current numeric umask and return the previous umask. 1280 1281 unlink(path, *, dir_fd=None) 1282 Remove a file (same as remove()). 1283 1284 If dir_fd is not None, it should be a file descriptor open to a directory, 1285 and path should be relative; path will then be relative to that directory. 1286 dir_fd may not be implemented on your platform. 1287 If it is unavailable, using it will raise a NotImplementedError. 1288 1289 urandom(size, /) 1290 Return a bytes object containing random bytes suitable for cryptographic use. 1291 1292 utime(path, times=None, *, ns=None, dir_fd=None, follow_symlinks=True) 1293 Set the access and modified time of path. 1294 1295 path may always be specified as a string. 1296 On some platforms, path may also be specified as an open file descriptor. 1297 If this functionality is unavailable, using it raises an exception. 1298 1299 If times is not None, it must be a tuple (atime, mtime); 1300 atime and mtime should be expressed as float seconds since the epoch. 1301 If ns is specified, it must be a tuple (atime_ns, mtime_ns); 1302 atime_ns and mtime_ns should be expressed as integer nanoseconds 1303 since the epoch. 1304 If times is None and ns is unspecified, utime uses the current time. 1305 Specifying tuples for both times and ns is an error. 1306 1307 If dir_fd is not None, it should be a file descriptor open to a directory, 1308 and path should be relative; path will then be relative to that directory. 1309 If follow_symlinks is False, and the last element of the path is a symbolic 1310 link, utime will modify the symbolic link itself instead of the file the 1311 link points to. 1312 It is an error to use dir_fd or follow_symlinks when specifying path 1313 as an open file descriptor. 1314 dir_fd and follow_symlinks may not be available on your platform. 1315 If they are unavailable, using them will raise a NotImplementedError. 1316 1317 waitpid(pid, options, /) 1318 Wait for completion of a given process. 1319 1320 Returns a tuple of information regarding the process: 1321 (pid, status << 8) 1322 1323 The options argument is ignored on Windows. 1324 1325 walk(top, topdown=True, onerror=None, followlinks=False) 1326 Directory tree generator. 1327 1328 For each directory in the directory tree rooted at top (including top 1329 itself, but excluding '.' and '..'), yields a 3-tuple 1330 1331 dirpath, dirnames, filenames 1332 1333 dirpath is a string, the path to the directory. dirnames is a list of 1334 the names of the subdirectories in dirpath (excluding '.' and '..'). 1335 filenames is a list of the names of the non-directory files in dirpath. 1336 Note that the names in the lists are just names, with no path components. 1337 To get a full path (which begins with top) to a file or directory in 1338 dirpath, do os.path.join(dirpath, name). 1339 1340 If optional arg 'topdown' is true or not specified, the triple for a 1341 directory is generated before the triples for any of its subdirectories 1342 (directories are generated top down). If topdown is false, the triple 1343 for a directory is generated after the triples for all of its 1344 subdirectories (directories are generated bottom up). 1345 1346 When topdown is true, the caller can modify the dirnames list in-place 1347 (e.g., via del or slice assignment), and walk will only recurse into the 1348 subdirectories whose names remain in dirnames; this can be used to prune the 1349 search, or to impose a specific order of visiting. Modifying dirnames when 1350 topdown is false is ineffective, since the directories in dirnames have 1351 already been generated by the time dirnames itself is generated. No matter 1352 the value of topdown, the list of subdirectories is retrieved before the 1353 tuples for the directory and its subdirectories are generated. 1354 1355 By default errors from the os.scandir() call are ignored. If 1356 optional arg 'onerror' is specified, it should be a function; it 1357 will be called with one argument, an OSError instance. It can 1358 report the error to continue with the walk, or raise the exception 1359 to abort the walk. Note that the filename is available as the 1360 filename attribute of the exception object. 1361 1362 By default, os.walk does not follow symbolic links to subdirectories on 1363 systems that support them. In order to get this functionality, set the 1364 optional argument 'followlinks' to true. 1365 1366 Caution: if you pass a relative pathname for top, don't change the 1367 current working directory between resumptions of walk. walk never 1368 changes the current directory, and assumes that the client doesn't 1369 either. 1370 1371 Example: 1372 1373 import os 1374 from os.path import join, getsize 1375 for root, dirs, files in os.walk('python/Lib/email'): 1376 print(root, "consumes", end="") 1377 print(sum([getsize(join(root, name)) for name in files]), end="") 1378 print("bytes in", len(files), "non-directory files") 1379 if 'CVS' in dirs: 1380 dirs.remove('CVS') # don't visit CVS directories 1381 1382 write(fd, data, /) 1383 Write a bytes object to a file descriptor. 1384 1385 DATA 1386 F_OK = 0 1387 O_APPEND = 8 1388 O_BINARY = 32768 1389 O_CREAT = 256 1390 O_EXCL = 1024 1391 O_NOINHERIT = 128 1392 O_RANDOM = 16 1393 O_RDONLY = 0 1394 O_RDWR = 2 1395 O_SEQUENTIAL = 32 1396 O_SHORT_LIVED = 4096 1397 O_TEMPORARY = 64 1398 O_TEXT = 16384 1399 O_TRUNC = 512 1400 O_WRONLY = 1 1401 P_DETACH = 4 1402 P_NOWAIT = 1 1403 P_NOWAITO = 3 1404 P_OVERLAY = 2 1405 P_WAIT = 0 1406 R_OK = 4 1407 SEEK_CUR = 1 1408 SEEK_END = 2 1409 SEEK_SET = 0 1410 TMP_MAX = 2147483647 1411 W_OK = 2 1412 X_OK = 1 1413 __all__ = ['altsep', 'curdir', 'pardir', 'sep', 'pathsep', 'linesep', ... 1414 altsep = '/' 1415 curdir = '.' 1416 defpath = r'.;C:\bin' 1417 devnull = 'nul' 1418 environ = environ({'ALLUSERSPROFILE': 'C:\\ProgramData', '...docguard ... 1419 extsep = '.' 1420 linesep = '\r\n' 1421 name = 'nt' 1422 pardir = '..' 1423 pathsep = ';' 1424 sep = r'\' 1425 supports_bytes_environ = False 1426 1427 FILE 1428 c:\users\jeremywu\appdata\local\programs\python\python37-32\lib\os.py 1429 1430 1431 None 1432 1433 进程已结束,退出代码0
针对日常的文件和目录管理任务,:mod:shutil 模块提供了一个易于使用的高级接口:
文件通配符
glob模块提供了一个函数用于从目录通配符搜索中生成文件列表:
输出:
['dir.py', 'FibonacciSeries.py', 'support.py', '函数.py', '异常处理.py', '循环语句.py', '时间相关和计划任务.py',
'条件控制.py', '标准库概况.py', '模块.py', '输入与输出.py', '迭代器与生成器.py', '面向对象.py']
命令行参数
通用工具脚本经常调用命令行参数。这些命令行参数以链表形式存储于 sys 模块的 argv 变量。例如在命令行中执行 "python demo.py one two three" 后可以得到以下输出结果:
>>> import sys
>>> print(sys.argv) ['demo.py', 'one', 'two', 'three']
错误输出重定向和程序终止
sys 还有 stdin,stdout 和 stderr 属性,即使在 stdout 被重定向时,后者也可以用于显示警告和错误信息。
>>> sys.stderr.write('Warning, log file not found starting a new one\n') Warning, log file not found starting a new one
大多脚本的定向终止都使用 "sys.exit()"。
字符串正则匹配
re模块为高级字符串处理提供了正则表达式工具。对于复杂的匹配和处理,正则表达式提供了简洁、优化的解决方案:
>>> import re
>>> re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest') ['foot', 'fell', 'fastest'] >>> re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat') 'cat in the hat'
如果只需要简单的功能,应该首先考虑字符串方法,因为它们非常简单,易于阅读和调试:
>>> 'tea for too'.replace('too', 'two') 'tea for two'
数学
math模块为浮点运算提供了对底层C函数库的访问:
>>> import math
>>> math.cos(math.pi / 4) 0.70710678118654757 >>> math.log(1024, 2) 10.0
random提供了生成随机数的工具。
>>> import random
>>> random.choice(['apple', 'pear', 'banana']) 'apple' >>> random.sample(range(100), 10) # sampling without replacement [30, 83, 16, 4, 8, 81, 41, 50, 18, 33] >>> random.random() # random float 0.17970987693706186 >>> random.randrange(6) # random integer chosen from range(6) 4
访问 互联网
有几个模块用于访问互联网以及处理网络通信协议。其中最简单的两个是用于处理从 urls 接收的数据的 urllib.request 以及用于发送电子邮件的 smtplib:
>>> from urllib.request import urlopen >>> for line in urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl'): ... line = line.decode('utf-8') # Decoding the binary data to text. ... if 'EST' in line or 'EDT' in line: # look for Eastern Time ... print(line) <BR>Nov. 25, 09:43:32 PM EST >>> import smtplib >>> server = smtplib.SMTP('localhost') >>> server.sendmail('[email protected]', '[email protected]', ... """To: [email protected] ... From: [email protected] ... ... Beware the Ides of March. ... """) >>> server.quit()
注意第二个例子需要本地有一个在运行的邮件服务器。
日期和时间
datetime模块为日期和时间处理同时提供了简单和复杂的方法。
支持日期和时间算法的同时,实现的重点放在更有效的处理和格式化输出。
该模块还支持时区处理:
>>> # dates are easily constructed and formatted
>>> from datetime import date >>> now = date.today() >>> now datetime.date(2003, 12, 2) >>> now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.") '12-02-03. 02 Dec 2003 is a Tuesday on the 02 day of December.' >>> # dates support calendar arithmetic >>> birthday = date(1964, 7, 31) >>> age = now - birthday >>> age.days 14368
数据压缩
以下模块直接支持通用的数据打包和压缩格式:zlib,gzip,bz2,zipfile,以及 tarfile。
>>> import zlib
>>> s = b'witch which has which witches wrist watch' >>> len(s) 41 >>> t = zlib.compress(s) >>> len(t) 37 >>> zlib.decompress(t) b'witch which has which witches wrist watch' >>> zlib.crc32(s) 226805979
性能度量
有些用户对了解解决同一问题的不同方法之间的性能差异很感兴趣。Python 提供了一个度量工具,为这些问题提供了直接答案。
例如,使用元组封装和拆封来交换元素看起来要比使用传统的方法要诱人的多,timeit 证明了现代的方法更快一些。
>>> from timeit import Timer >>> Timer('t=a; a=b; b=t', 'a=1; b=2').timeit() 0.57535828626024577 >>> Timer('a,b = b,a', 'a=1; b=2').timeit() 0.54962537085770791
相对于 timeit 的细粒度,:mod:profile 和 pstats 模块提供了针对更大代码块的时间度量工具。
测试模块
开发高质量软件的方法之一是为每一个函数开发测试代码,并且在开发过程中经常进行测试
doctest模块提供了一个工具,扫描模块并根据程序中内嵌的文档字符串执行测试。
测试构造如同简单的将它的输出结果剪切并粘贴到文档字符串中。
通过用户提供的例子,它强化了文档,允许 doctest 模块确认代码的结果是否与文档一致:
def average(values): """Computes the arithmetic mean of a list of numbers. >>> print(average([20, 30, 70])) 40.0 """ return sum(values) / len(values) import doctest doctest.testmod() # 自动验证嵌入测试
unittest模块不像 doctest模块那么容易使用,不过它可以在一个独立的文件里提供一个更全面的测试集:
import unittest class TestStatisticalFunctions(unittest.TestCase): def test_average(self): self.assertEqual(average([20, 30, 70]), 40.0) self.assertEqual(round(average([1, 5, 7]), 1), 4.3) self.assertRaises(ZeroDivisionError, average, []) self.assertRaises(TypeError, average, 20, 30, 70) unittest.main() # Calling from the command line invokes all tests
参考资料