python充电时刻

十章、充电时刻

python安装包里包含一组模块,标准库(standard library)。本章就重点讲讲这些标准库。

10.1模块

import从外部模块引入函数。

>>> import math
>>> math.sin(0)
0.0
>>> math.cos(0.)
1.0
>>> math.tan(0.)
0.0
>>> math.ctan(0)
Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    math.ctan(0)
AttributeError: 'module' object has no attribute 'ctan'
>>> math.cotan(0)
Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    math.cotan(0)
AttributeError: 'module' object has no attribute 'cotan'
>>> math.cot(0)
Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    math.cot(0)
AttributeError: 'module' object has no attribute 'cot'
>>> math.sec(0)
Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    math.sec(0)
AttributeError: 'module' object has no attribute 'sec'

10.1.1模块是程序

导入自己编写的模块

>>> import sys
>>> sys.path.append('D:Python32')#告诉系统除了从默认目录地方寻找模块外
>#还从该路径地址寻找
>>> import hello
What is your name?heh
Hello,heh!
>>> import hello
>>> 

再次导入模块并没有执行代码。
多次导入效果和导入一次效果相同。
python3之后没有reload函数重新导入操作了。

10.1.2模块用于定义

所谓模块就是编写的代码块被保存的名字。
1.在模块中定义函数

#模块保存为hello2.py
def hello():
    print("Hello,world!")
#运行结果
>>> import hello2#导入模块
>>> hello2.hello()#访问模块中的hello()函数
Hello,world!

这样为代码的复用提供了可能。一个已经写好的代码模块中的某些函数,可以被引入到现在正在编写的代码中,通过前面例子的方法引用模块中的函数,避免了代码的重复编写。
2.在模块中增加测试代码

#带有问题测试代码的简单模块
#hello3.py
def hello():
    print("Hello,world!")
#A test:
hello()
#运行结果
>>> import hello3#引入模块阶段,hello()函数就被执行了,这于前面hello2是不一样的,不是想要的
Hello,world!
>>> hello3.hello()
Hello,world!

怎么办?
就要告诉模块,是作为程序运行还是导入到其他程序。用到__name__变量

>>> __name__
'__main__'
>>> hello3.__name__
'hello3'

__name__变量的值是’__main__’。在导入模块时,这个变量被定义为模块的名字。

#带有问题测试代码的简单模块
#hello4.py
def hello():
    print("Hello,world!")
def test():
    hello()
if __name__=='__main__':test()#让模块被引入时,test函数不会执行。
#运行结果
>>> import hello4
>>> hello4.hello()
Hello,world!
>>> hello4.test()
Hello,world!
>>> hello4.__name__
'hello4'

if name == ‘main’ 如何正确理解?

10.1.3让自定义模块可用

两种方法:一是将模块放在正确的目录位置;二是引入时给出正确的路径。
1.将模块放在正确的位置
怎么做?
知道python解释器从哪里找模块就将自定义模块放在哪里就好了。一般放在
site-package目录下面
2.告诉解释器去哪里找
3.命名模块
.py命名后缀,或windows下.pyw后缀?没考证。

10.1.4包

把多个模块放在一组中,就是包。
例如你要建立一个drawing的包,其中包括shapes和colors的模块。就需要建立如下表所示的文件和目录。
简单的包布局

文件/目录 描述
~/python/ PYTHONPATH中的目录
~/python/drawing/ 包目录
~/python/drawing/__init__.py 包代码
~/python/drawing/colors.py colors模块
~/python/drawing/shapes.py shapes模块

windows系统中用c:\python替换~/python
三种引入语句
import drawing
import drawing.colors
from drawing import shapes

都合法

10.2探究模块

1、dir函数
查看模块包含的所有特性

import copy
>>> dir(copy)
['Error', 'PyStringMap', '_EmptyClass', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__name__', '__package__', '_copy_dispatch', '_copy_immutable', '_copy_with_constructor', '_copy_with_copy_method', '_deepcopy_atomic', '_deepcopy_dict', '_deepcopy_dispatch', '_deepcopy_list', '_deepcopy_method', '_deepcopy_tuple', '_keep_alive', '_reconstruct', '_test', 'builtins', 'copy', 'deepcopy', 'dispatch_table', 'error', 'name', 't', 'weakref']

2、__all__变量

>>> copy.__all__
['Error', 'copy', 'deepcopy']

定义模块的公有接口。

10.2.2用help获取帮助

>>> help(copy.copy)
Help on function copy in module copy:

copy(x)
    Shallow copy operation on arbitrary Python objects.
    
    See the module's __doc__ string for more info.


>>> print(copy.copy.__doc__)
Shallow copy operation on arbitrary Python objects.

    See the module's __doc__ string for more info.

查看某个模块除了help也可以直接看它的文档描述,如下例子所示。

>>> print(range.__doc__)
range([start,] stop[, step]) -> range object

Returns a virtual sequence of numbers from start to stop by step.

10.2.4查看模块的源代码

一种sys.path方法
一种查模块的__file__属性

>>> print(copy.__file__)
D:\Python32\lib\copy.py

就知道模块存储在哪个目录下。如果是.py就可以用python解释器直接打开。

10.3标准库

>>> import sys
>>> dir(sys)
['__displayhook__', '__doc__', '__excepthook__', '__name__', '__package__', '__stderr__', '__stdin__', '__stdout__', '_clear_type_cache', '_current_frames', '_getframe', '_mercurial', '_xoptions', 'api_version', 'argv', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dllhandle', 'dont_write_bytecode', 'exc_info', 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info', 'float_repr_style', 'getcheckinterval', 'getdefaultencoding', 'getfilesystemencoding', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'getswitchinterval', 'gettrace', 'getwindowsversion', 'hash_info', 'hexversion', 'int_info', 'intern', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'setcheckinterval', 'setprofile', 'setrecursionlimit', 'setswitchinterval', 'settrace', 'stderr', 'stdin', 'stdout', 'subversion', 'version', 'version_info', 'warnoptions', 'winver']
>>> print(sys.__doc__)
This module provides access to some objects used or maintained by the
interpreter and to functions that interact strongly with the interpreter.

Dynamic objects:

argv -- command line arguments; argv[0] is the script pathname if known
path -- module search path; path[0] is the script directory, else ''
modules -- dictionary of loaded modules

displayhook -- called to show results in an interactive session
excepthook -- called to handle any uncaught exception other than SystemExit
  To customize printing in an interactive session or to install a custom
  top-level exception handler, assign other functions to replace these.

stdin -- standard input file object; used by input()
stdout -- standard output file object; used by print()
stderr -- standard error object; used for error messages
  By assigning other file objects (or objects that behave like files)
  to these, it is possible to redirect all of the interpreter's I/O.

last_type -- type of last uncaught exception
last_value -- value of last uncaught exception
last_traceback -- traceback of last uncaught exception
  These three are only available in an interactive session after a
  traceback has been printed.

Static objects:

float_info -- a dict with information about the float implementation.
int_info -- a struct sequence with information about the int implementation.
maxsize -- the largest supported length of containers.
maxunicode -- the largest supported character
builtin_module_names -- tuple of module names built into this interpreter
subversion -- subversion information of the build as tuple
version -- the version of this interpreter as a string
version_info -- version information as a named tuple
hexversion -- version information encoded as a single integer
copyright -- copyright notice pertaining to this interpreter
platform -- platform identifier
executable -- pathname of this Python interpreter
prefix -- prefix used to find the Python library
exec_prefix -- prefix used to find the machine-specific Python library
float_repr_style -- string indicating the style of repr() output for floats
dllhandle -- [Windows only] integer handle of the Python DLL
winver -- [Windows only] version number of the Python DLL
__stdin__ -- the original stdin; don't touch!
__stdout__ -- the original stdout; don't touch!
__stderr__ -- the original stderr; don't touch!
__displayhook__ -- the original displayhook; don't touch!
__excepthook__ -- the original excepthook; don't touch!

Functions:

displayhook() -- print an object to the screen, and save it in builtins._
excepthook() -- print an exception and its traceback to sys.stderr
exc_info() -- return thread-safe information about the current exception
exit() -- exit the interpreter by raising SystemExit
getdlopenflags() -- returns flags to be used for dlopen() calls
getprofile() -- get the global profiling function
getrefcount() -- return the reference count for an object (plus one :-)
getrecursionlimit() -- return the max recursion depth for the interpreter
getsizeof() -- return the size of an object in bytes
gettrace() -- get the global debug tracing function
setcheckinterval() -- control how often the interpreter checks for events
setdlopenflags() -- set the flags to be used for dlopen() calls
setprofile() -- set the global profiling function
setrecursionlimit() -- set the max recursion depth for the interpreter
settrace() -- set the global debug tracing function
#百度解释
此模块提供对由
解释器和与解释器强交互的函数。
动态对象:
argv—命令行参数;argv[0]是脚本路径名(如果已知)
path—模块搜索路径;路径[0]是脚本目录,否则为''
模块加载模块字典
displayhook——调用以在交互式会话中显示结果
ExceptHook——调用它来处理除SystemExit之外的任何未捕获异常
在交互式会话中自定义打印或安装自定义
顶级异常处理程序,分配其他函数来替换它们。
stdin——标准输入文件对象;由input()使用
stdout——标准输出文件对象;由print()使用
stderr——标准错误对象;用于错误消息
通过指定其他文件对象(或行为类似于文件的对象)
对于这些,可以重定向解释器的所有I/O。
last_type—最后一个未捕获异常的类型
last_value—最后一个未捕获异常的值
last_traceback—上次未捕获异常的跟踪
只有在
已打印回溯。
静态对象:
float_info——包含float实现信息的dict。
int_info——一个包含int实现信息的结构序列。
MaxSize——容器的最大支持长度。
maxUnicode——支持的最大字符
内置模块名——内置到这个解释器中的模块名元组
subversion——以元组形式生成的subversion信息
version——这个解释器作为字符串的版本
版本信息——作为命名元组的版本信息
hexversion—编码为单个整数的版本信息
版权——与本翻译相关的版权声明
平台——平台标识符
可执行文件——这个python解释器的路径名
prefix——用于查找python库的前缀
exec_prefix——用于查找特定于机器的python库的前缀
float_repr_style——表示float的repr()输出样式的字符串
dll handle--[windows only]python dll的整数句柄
winver--[windows only]python dll的版本号
_原版stdin;不要碰!
_原版stdout;不要碰!
_斯特德——原来的斯特德;不要碰!
_ displayhook——原来的displayhook;不要碰!
_ ExceptHook——原来的ExceptHook;不要碰!
功能:
displayHook()——将对象打印到屏幕上,并将其保存在内置文件中。_
excepthook()--打印异常及其对sys.stderr的回溯
exc_info()--返回当前异常的线程安全信息
exit()--通过提升systemexit退出解释器
getdlopenflags()--返回用于dlopen()调用的标志
getprofile()--获取全局分析函数
getRefCount()--返回对象的引用计数(加一:-)
getRecursionLimit()--返回解释器的最大递归深度
getsizeof()--返回对象的大小(字节)
gettrace()--获取全局调试跟踪函数
setcheckinterval()——控制解释器检查事件的频率
set dlopen flags()--设置用于dlopen()调用的标志
setprofile()--设置全局分析函数
setRecursionLimit()--设置解释器的最大递归深度
setTrace()--设置全局调试跟踪函数

Python中 sys.argv[]的用法详解https://www.cnblogs.com/aland-1415/p/6613449.html

#reverseargs.py
import sys
args=sys.argv[1:]
args.reverse()
print(' '.join(args))

运行结果

10.3.2 os

os提供访问多个操作系统的服务

>>> import os
>>> print(os.__doc__)
OS routines for Mac, NT, or Posix depending on what system we're on.

This exports:
  - all functions from posix, nt, os2, or ce, e.g. unlink, stat, etc.
  - os.path is either posixpath or ntpath
  - os.name is either 'posix', 'nt', 'os2' or 'ce'.
  - os.curdir is a string representing the current directory ('.' or ':')
  - os.pardir is a string representing the parent directory ('..' or '::')
  - os.sep is the (or a most common) pathname separator ('/' or ':' or '\\')
  - os.extsep is the extension separator (always '.')
  - os.altsep is the alternate pathname separator (None or '/')
  - os.pathsep is the component separator used in $PATH etc
  - os.linesep is the line separator in text files ('\r' or '\n' or '\r\n')
  - os.defpath is the default search path for executables
  - os.devnull is the file path of the null device ('/dev/null', etc.)

Programs that import and use 'os' stand a better chance of being
portable between different platforms.  Of course, they must then
only use functions that are defined by all platforms (e.g., unlink
and opendir), and leave all pathname manipulation to os.path
(e.g., split and join).
#百度解释
Mac、NT或POSIX的操作系统例程取决于我们所使用的系统。
此导出:
-来自POSIX、NT、OS2或CE的所有函数,例如unlink、stat等。
-os.path是posixpath或ntpath
-os.name可以是'posix'、'nt'、'os2'或'ce'。
-os.curdir是一个字符串,表示当前目录('.'或':')
-os.pardir是表示父目录(“..”或“::”)的字符串。
-os.sep是(或最常见的)路径名分隔符('/'或':'或'\')
-os.extsep是扩展分隔符(总是“.”)
-os.altsep是备用路径名分隔符(无或“/”)
-os.pathsep是$path etc中使用的组件分隔符
-os.linesep是文本文件中的行分隔符('\r'或'\n'或'\r\n')
-os.defpath是可执行文件的默认搜索路径
-os.dev null是空设备('/dev/null'等)的文件路径。
导入和使用“os”的程序更有可能
可在不同平台之间移动。当然,他们必须
仅使用所有平台定义的函数(例如,取消链接
和opendir),并将所有路径名操作留给os.path
(例如,拆分和连接)。

windows下调用以下代码

>>> import os
>>> os.system(r'D:\"Program Files"\"Thunder Network"\"Thunder"\"Program"\ThunderStart.exe')
0
#出现0,表示程序启动成功,实际情况也是迅雷被启动,启动之前会弹出dos窗口。
>>> os.system(r'D:\"Program Files"\"Thunder Network"\Thunder\Program\ThunderStart.exe')
0
#同样效果
>>> os.system(r'D:\"Program Files"\Thunder Network\Thunder\Program\ThunderStart.exe')
1
#失败的结果

Program Files
Thunder Network
必须放在引号中,不然dos会在空格处停下来。
使用另一种windows特有方法os.startfile能解决问题。

>>> os.startfile(r'D:\Program Files\Thunder Network\Thunder\Program\ThunderStart.exe')
#启动了迅雷,没有返回值0或1,也没有弹出dos窗口

这种方法就算有空格也不会有影响。

10.3.3 fileinput

>>> import fileinput
>>> dir(fileinput)
['DEFAULT_BUFSIZE', 'FileInput', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__name__', '__package__', '_state', '_test', 'close', 'filelineno', 'filename', 'fileno', 'hook_compressed', 'hook_encoded', 'input', 'isfirstline', 'isstdin', 'lineno', 'nextfile', 'os', 'sys']
>>> dir(fileinput.__all__)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
>>> print(fileinput.__all__)
['FileInput', 'close', 'filelineno', 'filename', 'input', 'isfirstline', 'isstdin', 'lineno', 'nextfile']
>>> fileinput.__all__
['FileInput', 'close', 'filelineno', 'filename', 'input', 'isfirstline', 'isstdin', 'lineno', 'nextfile']
>>> help(fileinput)
Help on module fileinput:

NAME
    fileinput - Helper class to quickly write a loop over all standard input files.

DESCRIPTION
    Typical use is:
    
        import fileinput
        for line in fileinput.input():
            process(line)
    
    This iterates over the lines of all files listed in sys.argv[1:],
    defaulting to sys.stdin if the list is empty.  If a filename is '-' it
    is also replaced by sys.stdin.  To specify an alternative list of
    filenames, pass it as the argument to input().  A single file name is
    also allowed.
    
    Functions filename(), lineno() return the filename and cumulative line
    number of the line that has just been read; filelineno() returns its
    line number in the current file; isfirstline() returns true iff the
    line just read is the first line of its file; isstdin() returns true
    iff the line was read from sys.stdin.  Function nextfile() closes the
    current file so that the next iteration will read the first line from
    the next file (if any); lines not read from the file will not count
    towards the cumulative line count; the filename is not changed until
    after the first line of the next file has been read.  Function close()
    closes the sequence.
    
    Before any lines have been read, filename() returns None and both line
    numbers are zero; nextfile() has no effect.  After all lines have been
    read, filename() and the line number functions return the values
    pertaining to the last line read; nextfile() has no effect.
    
    All files are opened in text mode by default, you can override this by
    setting the mode parameter to input() or FileInput.__init__().
    If an I/O error occurs during opening or reading a file, the IOError
    exception is raised.
    
    If sys.stdin is used more than once, the second and further use will
    return no lines, except perhaps for interactive use, or if it has been
    explicitly reset (e.g. using sys.stdin.seek(0)).
    
    Empty files are opened and immediately closed; the only time their
    presence in the list of filenames is noticeable at all is when the
    last file opened is empty.
    
    It is possible that the last line of a file doesn't end in a newline
    character; otherwise lines are returned including the trailing
    newline.
    
    Class FileInput is the implementation; its methods filename(),
    lineno(), fileline(), isfirstline(), isstdin(), nextfile() and close()
    correspond to the functions in the module.  In addition it has a
    readline() method which returns the next input line, and a
    __getitem__() method which implements the sequence behavior.  The
    sequence must be accessed in strictly sequential order; sequence
    access and readline() cannot be mixed.
    
    Optional in-place filtering: if the keyword argument inplace=1 is
    passed to input() or to the FileInput constructor, the file is moved
    to a backup file and standard output is directed to the input file.
    This makes it possible to write a filter that rewrites its input file
    in place.  If the keyword argument backup=".<some extension>" is also
    given, it specifies the extension for the backup file, and the backup
    file remains around; by default, the extension is ".bak" and it is
    deleted when the output file is closed.  In-place filtering is
    disabled when standard input is read.  XXX The current implementation
    does not work for MS-DOS 8+3 filesystems.
    
    Performance: this module is unfortunately one of the slower ways of
    processing large numbers of input lines.  Nevertheless, a significant
    speed-up has been obtained by using readlines(bufsize) instead of
    readline().  A new keyword argument, bufsize=N, is present on the
    input() function and the FileInput() class to override the default
    buffer size.
    
    XXX Possible additions:
    
    - optional getopt argument processing
    - isatty()
    - read(), read(size), even readlines()

CLASSES
    builtins.object
        FileInput
    
    class FileInput(builtins.object)
     |  class FileInput([files[, inplace[, backup[, mode[, openhook]]]]])
     |  
     |  Class FileInput is the implementation of the module; its methods
     |  filename(), lineno(), fileline(), isfirstline(), isstdin(), fileno(),
     |  nextfile() and close() correspond to the functions of the same name
     |  in the module.
     |  In addition it has a readline() method which returns the next
     |  input line, and a __getitem__() method which implements the
     |  sequence behavior. The sequence must be accessed in strictly
     |  sequential order; random access and
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值