【问题标题】:Parse a git URL like 'ssh://git@gitlab.org.net:3333/org/repo.git'?解析像“ssh://git@gitlab.org.net:3333/org/repo.git”这样的 git URL?
【发布时间】:2016-04-21 20:43:38
【问题描述】:

我怎样才能轻松地从像ssh://git@gitlab.org.net:3333/org/repo.git 这样的 git URL 中提取主机名

u = urlparse(s)

给我

ParseResult(scheme='ssh', netloc='git@gitlab.org.net:3333', path='/org/repo.git', params='', query='', fragment='')

这意味着 netloc 最接近我想要的,这给我留下了令人失望的工作量。

我应该这样做

u.netloc.split('@')[1].split(':')[0]

或者有没有更好的库处理它?

【问题讨论】:

    标签: python parsing url-parsing urlparse


    【解决方案1】:

    返回的ParseResult 有一个hostname 属性:

    >>> urlparse('ssh://git@gitlab.org.net:3333/org/repo.git').hostname
    'gitlab.org.net'
    

    【讨论】:

    【解决方案2】:

    使用标准库 urlparse 将无法解析许多有效的 git URL。

    >>> from urllib.parse import urlparse
    >>> urlparse('git@github.com:Org/Private-repo.git')
    ParseResult(scheme='', netloc='', path='git@github.com:Org/Private-repo.git', params='', query='', fragment='')
    

    https://pypi.python.org/pypi/git-url-parse 是一个相当不错的 git URL 解析器,其接口与urlparse 相似。

    >>> import giturlparse
    >>> url = giturlparse.parse('ssh://git@gitlab.com:3333/org/repo.git')
    >>> url
    Parsed(pathname='/org/repo.git', protocols=['ssh'], protocol='ssh', href='ssh://git@gitlab.com:3333/org/repo.git', resource='gitlab.com', user='git', port='3333', name='repo', owner='org')
    >>> url.resource
    'gitlab.com'
    

    https://pypi.org/project/giturlparse/ 是另一个最近更新的,使用类似的 API。

    请注意,这两个 PyPI 包都安装到目录 giturlparse,因此它们相互冲突,但由于具有相似的 API,它们几乎可以互换。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-18
      • 1970-01-01
      • 1970-01-01
      • 2016-09-29
      • 2015-09-20
      • 1970-01-01
      • 2018-10-11
      • 1970-01-01
      相关资源
      最近更新 更多