源码阅读学习笔记- 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. web site web site 发布于 2020年11月30日 02:30 #

    Hi there, You've done an excellent job. I will definitely digg it and personally recommend tto
    my friends. I am sure they'll be benefited from this site.

    запчасти опель web site запчасти suzuki

  2. cfysu.com cfysu.com 发布于 2020年11月30日 03:49 #

    I read tһis post fuⅼly regarding the difference of most recent and earlier technologies,
    іt's awеsome articlе. http://Cfysu.com/comment/html/?165394.html

  3. Joesph Joesph 发布于 2020年11月30日 04:19 #

    Thanks for one's marvelous posting! I quite enjoyed reading it, you
    are a great author.I will be sure to bookmark your blog and will often come back very soon. I want to encourage continue your great writing, have a nice day!

  4. Joesph Joesph 发布于 2020年11月30日 04:19 #

    Thanks for one's marvelous posting! I quite enjoyed reading it, you are a great author.I will be sure to bookmark your blog and will
    often come back very soon. I want to encourage continue your great
    writing, have a nice day!

  5. swimming pool contractors swimming pool contractors 发布于 2020年11月30日 04:20 #

    It's an remarkable post designed for all the web visitors

  6. 디올오피 디올오피 发布于 2020年11月30日 05:42 #

    Thanks , I have recently been looking for info approximately
    this topic for a long time and yours is the greatest I have came upon till
    now. However, what concerning the conclusion? Are
    you certain in regards to the supply?

  7. 디올오피 디올오피 发布于 2020年11月30日 05:43 #

    Thanks , I have recently been looking for info approximately this topic
    for a long time and yours is the greatest I have came upon till now.
    However, what concerning the conclusion? Are you certain in regards to the supply?

  8. Japanese Sex Japanese Sex 发布于 2020年11月30日 05:57 #

    Nice blog right here! Also your web site loads up fast!
    What host are you the usage of? Can I get your associate link for your host?
    I want my website loaded up as quickly as yours lol

  9. Japanese Sex Japanese Sex 发布于 2020年11月30日 05:57 #

    Nice blog right here! Also your web site loads up fast!

    What host are you the usage of? Can I get your associate link for your host?
    I want my website loaded up as quickly as yours lol

  10. how to get google play gift card how to get google play gift card 发布于 2020年11月30日 06:36 #

    Oh my goodness! Incredible article dude! Thank you, However
    I am encountering issues with your RSS. I don't understand why I
    cannot subscribe to it. Is there anybody getting identical RSS issues?
    Anybody who knows the solution will you kindly respond?
    Thanks!!

  11. how to get google play gift card how to get google play gift card 发布于 2020年11月30日 06:36 #

    Oh my goodness! Incredible article dude!

    Thank you, However I am encountering issues with your RSS. I don't understand why I cannot subscribe
    to it. Is there anybody getting identical RSS issues?
    Anybody who knows the solution will you kindly respond? Thanks!!

  12. gutters and downspouts gutters and downspouts 发布于 2020年11月30日 07:02 #

    Helpful information. Lucky me I found your site unintentionally, and I'm surprised why this accident didn't came about in advance!
    I bookmarked it.

  13. gutters and downspouts gutters and downspouts 发布于 2020年11月30日 07:02 #

    Helpful information. Lucky me I found your site unintentionally, and I'm
    surprised why this accident didn't came about in advance!
    I bookmarked it.

  14. dominoqq dominoqq 发布于 2020年11月30日 07:04 #

    Hеllo!І just wanteed to ask if yyou evеr have any problemѕ witһ haсkers?
    My last bⅼog (wordpress) was hacked and I ended up losing
    months of hard w᧐rk due to no data Ƅackup. Do you have ɑny metһods to prevent haсkers? http://Sdongha.com/?document_srl=2434061

  15. 수원출장마사지 수원출장마사지 发布于 2020年11月30日 07:23 #

    you're truly a good webmaster. The website loading pace is incredible.

    It seems that you are doing any distinctive trick.
    Also, The contents are masterwork. you've performed a fantastic process in this subject!

  16. 수원출장마사지 수원출장마사지 发布于 2020年11月30日 07:23 #

    you're truly a good webmaster. The website loading pace is
    incredible. It seems that you are doing any distinctive trick.
    Also, The contents are masterwork. you've performed a fantastic process in this subject!

  17. seo продвижение в Минске seo продвижение в Минске 发布于 2020年11月30日 07:38 #

    It's actually a great and useful piece of information. I'm happy that you shared this useful
    info with us. Please keep us up to date like this.

    Thank you for sharing.

  18. seo продвижение в Минске seo продвижение в Минске 发布于 2020年11月30日 07:38 #

    It's actually a great and useful piece of information. I'm happy that you shared
    this useful info with us. Please keep us up to date like this.

    Thank you for sharing.

  19. http://wwbtx.com/comment/html/?163440.html http://wwbtx.com/comment/html/?163440.html 发布于 2020年11月30日 07:50 #

    Magnificent ցoods from you, man. I have understand your stuff
    previous to and you are just too exceⅼlent. I actually like what
    you have aacqսired here, really like whatt you're
    statig and the way in which you say it. You make it enjoyable and you still care for
    to keep it sensіble. I can not wait to reɑd fɑr
    moгe from you. This iѕ adtually a teгrific website. http://wwbtx.com/comment/html/?163440.html

  20. sexrose.com sexrose.com 发布于 2020年11月30日 07:59 #

    What's up, just wanted to tell you, I enjoyed this blog post.
    It was helpful. Keep on posting!

  21. sexrose.com sexrose.com 发布于 2020年11月30日 08:00 #

    What's up, just wanted to tell you, I enjoyed this blog post.

    It was helpful. Keep on posting!

  22. generic cialis tadalafil generic cialis tadalafil 发布于 2020年11月30日 08:03 #

    We are a group of volunteers and starting a brand
    new scheme in our community. Your web site offered us with helpful info to work on.
    You've performed an impressive job and our whole neighborhood will be thankful to you.

  23. generic cialis tadalafil generic cialis tadalafil 发布于 2020年11月30日 08:03 #

    We are a group of volunteers and starting a brand new scheme in our community.

    Your web site offered us with helpful info to work on. You've performed an impressive job and our whole neighborhood will be thankful to
    you.

发表评论