程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python from door to mastery (II): packaging-07-modules and packages

編輯:Python

One 、 modular

1.1、__init__.py

Create... Under each folder __init__.py file , This file will be executed before importing the specific modules under this package . It can define some contents related to modules . Like publishing : The following code only imports spam and grok. If the from module import * All modules that do not begin with an underscore will be imported . But if defined __all__ Only the listed modules will be imported , If you define an empty list , No modules will be imported .

def
spam():

pass

def grok():
pass

age = 30
# Only export 'spam' and 'grok'
__all__ = [ 'spam', 'grok']
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.

Reload , This method is not recommended for use in production environments .

import
importlib

from chapter10 import module_split

importlib. reload( module_split)
  • 1.
  • 2.
  • 3.
  • 4.

Through the string import module

req
=
importlib.
import_module(
'requests')

res = req. get( 'http://www.python.org')
  • 1.
  • 2.

1.2、 Hook function

import
importlib

import sys
from collections import defaultdict

_post_import_hooks = defaultdict( list)

class PostImportFinder:
def __init__( self):
self. _skip = set()

def find_module( self, full_name, path = None):
if full_name in self. _skip:
return None
self. _skip. add( full_name)
return PostImportLoader( self)

class PostImportLoader:
def __init__( self, finder):
self. _finder = finder

def load_module( self, full_name):
importlib. import_module( full_name)
module = sys. modules[ full_name]
for func in _post_import_hooks[ full_name]:
func( module)
self. _finder. _skip. remove( full_name)
return module

def imported_action( full_name):
def decorate( func):
if full_name in sys. modules:
func( sys. modules[ full_name])
else:
_post_import_hooks[ full_name]. append( func)
return func
return decorate

sys. meta_path. insert( 0, PostImportFinder())

@ imported_action( 'threading')
def warn_threads( mod):
print( 'Call Threads.')
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.

Add decorators to existing function definitions ,imported_action The decorator is used to register the processor functions activated during import . This decorator is used to inspect sys.modules, To see if the module has been loaded . If it is , The processor is immediately called , Add to _post_improts_hooks A list of dictionaries . A module can register multiple processors ,_post_import_hooks Is used to collect all the processor objects .

from
functools
import
wraps

from chapter10. modify_module import imported_action

def logged( func):
@ wraps( func)
def wrapper( * args, * * kwargs):
print( f'Calling { func. __name__} ,args: { args} ,kwargs: { kwargs} ')
return func( * args, * * kwargs)
return wrapper

@ imported_action( 'math')
def add_logging( mod):
mod. cos = logged( mod. cos)
mod. sin = logged( mod. sin)


import math
print( f'math.sin(2) = { math. sin( 2)} ')
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.

Two 、 package

2.1、 Common use

2.1.1、 Read the data file in the package

import
pkgutil

data = pkgutil. get_data( __package__, 'test_data.dat') # The first function can use the package name directly .
  • 1.
  • 2.

2.1.2、 Add folder to sys.path

This function is similar to dynamically adding libraries to path Under the path .site-package The directory is the directory where the third-party packages and modules are installed . If you install the code manually , The code will be installed in site-package Under the table of contents . To configure path Of pth The file must be placed in site-packages in , But the configured path can be in any desired directory on the system .

import
sys

print( f'sys path: { sys. path} ')


import sys
sys. path. insert( 0, '/test/dir')
sys. path. insert( 0, '/test/dir')


import sys
from os import path
file_path = path. abspath( path. dirname( __file__))
sys. path. insert( 0, path. join( file_path, 'test'))
print( f'sys path: { sys. path} ')
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.

2.2、 Package distribution

This function is similar to java Inside maven Private service function . Upload module for other applications dependency.

#step1: To write setup.py file 


from distutils. core import setup

setup( name = 'projectname',
version = '1.0',
author = 'Your Name',
author_email = '[email protected]',
url = 'http://www.you.com/projectname',
packages =[ 'projectname', 'projectname.utils'],
)

#setp2: establish MANIFEST.INF file
include *. txt
recursive - include examples *
recursive - include Doc *

#setp3: Execute command release
python3 setup. py sdist
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.



  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved