源码阅读学习笔记- kennethreitz/pip-pop:Tools for managing requirements files.

用途对比 依赖包之间的差异
学习总结:
1、super() 以及 __init__ 区别,作用
2、''' '''doc 文档内容定义,借助docopt 模块
3、活用if表达式赋值

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""Usage:
  pip-diff (--fresh | --stale) <reqfile1> <reqfile2> [--exclude <package>...]
  pip-diff (-h | --help)
Options:
  -h --help     Show this screen.
  --fresh       List newly added packages.
  --stale       List removed packages.
"""
import os
from docopt import docopt                                  #根据''' ''' doc内容自动生成命令行参数解析器,常用于显示命令帮助信息
from pip.req import parse_requirements
from pip.index import PackageFinder
from pip._vendor.requests import session

requests = session()


class Requirements(object):
    def __init__(self, reqfile=None):
        super(Requirements, self).__init__()   # super 与 init 区别 ,super 递归访问给定cls 的上一级
        self.path = reqfile
        self.requirements = []

        if reqfile:
            self.load(reqfile)

    def __repr__(self):                                  # 返回可见的字符串,对机器友好 区别于__str__
        return '<Requirements \'{}\'>'.format(self.path)

    def load(self, reqfile):
        if not os.path.exists(reqfile):
            raise ValueError('The given requirements file does not exist.')

        finder = PackageFinder([], [], session=requests)
        for requirement in parse_requirements(reqfile, finder=finder, session=requests):
            if requirement.req:
                if not getattr(requirement.req, 'name', None):
                    # Prior to pip 8.1.2 the attribute `name` did not exist.
                    requirement.req.name = requirement.req.project_name
                self.requirements.append(requirement.req)


    def diff(self, requirements, ignore_versions=False, excludes=None):
        r1 = self      # 类本身
        r2 = requirements
        results = {'fresh': [], 'stale': []}

        # Generate fresh packages.
        other_reqs = ( 
            [r.name for r in r1.requirements]  # 常见的列表推导式 ,r1.requirements 访问类本身的属性
            if ignore_versions else r1.requirements   # if表达式中 赋值,  if True other_reqs =  [r.name for r in r1.requirements] ;else other_reqs = r1.requirements
        )

        for req in r2.requirements:
            r = req.name if ignore_versions else req

            if r not in other_reqs and r not in excludes:
                results['fresh'].append(req)

        # Generate stale packages.
        other_reqs = (
            [r.name for r in r2.requirements]
            if ignore_versions else r2.requirements
        )

        for req in r1.requirements:
            r = req.name if ignore_versions else req

            if r not in other_reqs and r not in excludes:
                results['stale'].append(req)

        return results


def diff(r1, r2, include_fresh=False, include_stale=False, excludes=None):
    include_versions = True if include_stale else False
    excludes = excludes if len(excludes) else []  # 这货  if 表达式赋值 用的6

    try:
        r1 = Requirements(r1)
        r2 = Requirements(r2)
    except ValueError:
        print('There was a problem loading the given requirements files.')
        exit(os.EX_NOINPUT)

    results = r1.diff(r2, ignore_versions=True, excludes=excludes)

    if include_fresh:
        for line in results['fresh']:
            print(line.name if include_versions else line)

    if include_stale:
        for line in results['stale']:
            print(line.name if include_versions else line)


def main():
    args = docopt(__doc__, version='pip-diff')

    kwargs = {                                        # 获取参数  值得学习
        'r1': args['<reqfile1>'],
        'r2': args['<reqfile2>'],
        'include_fresh': args['--fresh'],
        'include_stale': args['--stale'],
        'excludes': args['<package>']
    }

    diff(**kwargs)


if __name__ == '__main__':
main()

Pingbacks已打开。

引用地址

评论
  1. situs idn poker situs idn poker 发布于 2021年3月9日 01:33 #

    My programmer is trying to persuade me to move to .net from PHP.

    I have always disliked the idea because of the costs.
    But he's tryiong none the less. I've been using WordPress on several websites
    for about a year and am anxious about switching to another platform.

    I have heard excellent things about blogengine.net.
    Is there a way I can transfer all my wordpress content into it?
    Any kind of help would be really appreciated!

  2. situs idn poker situs idn poker 发布于 2021年3月9日 01:33 #

    My programmer is trying to persuade me to move to .net from
    PHP. I have always disliked the idea because of the costs.
    But he's tryiong none the less. I've been using WordPress on several websites for
    about a year and am anxious about switching to another platform.
    I have heard excellent things about blogengine.net.
    Is there a way I can transfer all my wordpress content into
    it? Any kind of help would be really appreciated!

  3. brain Injury Lawyers toronto brain Injury Lawyers toronto 发布于 2021年3月9日 01:37 #

    A skilled mind injury lawyer might have the ability to help.

  4. Bitcoin kasinobonukset 2021 Bitcoin kasinobonukset 2021 发布于 2021年3月9日 01:40 #

    Good day! I know this is somewhat off topic but I was wondering if you knew where I could get a captcha plugin for my comment form?
    I'm using the same blog platform as yours and I'm having trouble finding
    one? Thanks a lot!

  5. Bitcoin kasinobonukset 2021 Bitcoin kasinobonukset 2021 发布于 2021年3月9日 01:40 #

    Good day! I know this is somewhat off topic but I was wondering if you knew where I could get a captcha plugin for my comment form?
    I'm using the same blog platform as yours and I'm having trouble
    finding one? Thanks a lot!

  6. bike lights amazon australia bike lights amazon australia 发布于 2021年3月9日 01:40 #

    Ride safely in the evening with these bike lights.

  7. item351138005 item351138005 发布于 2021年3月9日 01:41 #

    The mind injury lawyers at DE CARO & KAPLEN, LLP.

  8. bike lights amazon prime bike lights amazon prime 发布于 2021年3月9日 01:43 #

    Comes with a tiny usb cord, radiates brilliantly.

  9. solar company in selangor solar company in selangor 发布于 2021年3月9日 01:44 #

    This is very attention-grabbing, You are an overly skilled blogger.
    I've joined your rss feed and sit up for looking
    for more of your fantastic post. Additionally, I've shared your site in my social networks

  10. solar company in selangor solar company in selangor 发布于 2021年3月9日 01:44 #

    This is very attention-grabbing, You are an overly skilled blogger.
    I've joined your rss feed and sit up for looking for more of your fantastic post.
    Additionally, I've shared your site in my social networks

  11. PaulGal PaulGal 发布于 2021年3月9日 01:44 #

    <a href="https://efftablets.com/">canadian pharmacy without prescription</a> <a href="https://ycialis.com/">cialis 5mg price in canada</a> <a href="https://ddvrx.com/">phenergan 10mg over the counter</a> <a href="https://pllzshop.com/">gabapentin 100 mg capsule</a> <a href="https://buyimedications.com/">wellbutrin 100mg tablets</a>

发表评论