标签归档:github

在Markdown和reStructuredText中都具有相同的自述文件

问题:在Markdown和reStructuredText中都具有相同的自述文件

我有一个托管在GitHub上的项目。为此,我使用Markdown语法编写了自述文件,以便在GitHub上很好地格式化它。

由于我的项目使用Python,因此我还计划将其上传到PyPi。PyPi上用于README的语法为reStructuredText。

我希望避免处理两个包含大致相同内容的自述文件。因此,我搜索了RST(或相反)转换器的降价促销,但找不到任何商品。

我看到的另一个解决方案是执行markdown / HTML,然后执行HTML / RST转换。我在这里这里都找到了一些资源,所以我猜应该是可行的。

您有什么想法可以更好地适合我的工作吗?

I have a project hosted on GitHub. For this I have written my README using the Markdown syntax in order to have it nicely formatted on GitHub.

As my project is in Python I also plan to upload it to PyPi. The syntax used for READMEs on PyPi is reStructuredText.

I would like to avoid having to handle two READMEs containing roughly the same content; so I searched for a markdown to RST (or the other way around) translator, but couldn’t find any.

The other solution I see is to perform a markdown/HTML and then a HTML/RST translation. I found some ressources for this here and here so I guess it should be possible.

Would you have any idea that could fit better with what I want to do?


回答 0

我会推荐Pandoc,“将文件从一种标记格式转换为另一种格式的瑞士军刀”(在页面底部查看受支持的转换图,这是非常令人印象深刻的)。Pandoc允许markdown直接进行reStructuredText翻译。此外,还有一个在线编辑器,在这里它可以让你尝试一下,所以你可以简单地使用在线编辑器来转换你的自述文件。

I would recommend Pandoc, the “swiss-army knife for converting files from one markup format into another” (check out the diagram of supported conversions at the bottom of the page, it is quite impressive). Pandoc allows markdown to reStructuredText translation directly. There is also an online editor here which lets you try it out, so you could simply use the online editor to convert your README files.


回答 1

正如@Chris建议的那样,您可以使用Pandoc将Markdown转换为RST。这可以使用pypandoc模块和setup.py中的一些魔术来简单地自动化:

from setuptools import setup
try:
    from pypandoc import convert
    read_md = lambda f: convert(f, 'rst')
except ImportError:
    print("warning: pypandoc module not found, could not convert Markdown to RST")
    read_md = lambda f: open(f, 'r').read()

setup(
    # name, version, ...
    long_description=read_md('README.md'),
    install_requires=[]
)

对于在PyPi上使用的详细说明,这将自动将README.md转换为RST。当pypandoc不可用时,它将仅读取README.md而不进行转换-不会在其他人只想构建模块而不上传到PyPi时不强迫其他人安装pypandoc。

因此,您可以像往常一样在Markdown中编写内容,而不再关心RST混乱了。;)

As @Chris suggested, you can use Pandoc to convert Markdown to RST. This can be simply automated using pypandoc module and some magic in setup.py:

from setuptools import setup
try:
    from pypandoc import convert
    read_md = lambda f: convert(f, 'rst')
except ImportError:
    print("warning: pypandoc module not found, could not convert Markdown to RST")
    read_md = lambda f: open(f, 'r').read()

setup(
    # name, version, ...
    long_description=read_md('README.md'),
    install_requires=[]
)

This will automatically convert README.md to RST for the long description using on PyPi. When pypandoc is not available, then it just reads README.md without the conversion – to not force others to install pypandoc when they wanna just build the module, not upload to PyPi.

So you can write in Markdown as usual and don’t care about RST mess anymore. ;)


回答 2

2019更新

PyPI Warehouse 现在也支持渲染Markdown!您只需要更新软件包配置并将其添加long_description_content_type='text/markdown'到其中即可。例如:

setup(
    name='an_example_package',
    # other arguments omitted
    long_description=long_description,
    long_description_content_type='text/markdown'
)

因此,无需再将README保留为两种格式。

您可以在文档中找到有关它的更多信息。

旧答案:

GitHub使用的标记库支持reStructuredText。这意味着您可以编写README.rst文件。

它们甚至使用codecode-block指令支持语法特定的颜色突出显示(示例

2019 Update

The PyPI Warehouse now supports rendering Markdown as well! You just need to update your package configuration and add the long_description_content_type='text/markdown' to it. e.g.:

setup(
    name='an_example_package',
    # other arguments omitted
    long_description=long_description,
    long_description_content_type='text/markdown'
)

Therefore, there is no need to keep the README in two formats any longer.

You can find more information about it in the documentation.

Old answer:

The Markup library used by GitHub supports reStructuredText. This means you can write a README.rst file.

They even support syntax specific color highlighting using the code and code-block directives (Example)


回答 3

PyPI现在支持Markdown进行详细描述!

在中setup.py,设置long_description为Markdown字符串,添加long_description_content_type="text/markdown"并确保您使用的是最新工具(setuptools38.6.0 +,twine1.11 +)。

有关更多详细信息,请参见Dustin Ingram的博客文章

PyPI now supports Markdown for long descriptions!

In setup.py, set long_description to a Markdown string, add long_description_content_type="text/markdown" and make sure you’re using recent tooling (setuptools 38.6.0+, twine 1.11+).

See Dustin Ingram’s blog post for more details.


回答 4

根据我的要求,我不想在计算机上安装Pandoc。我用了docverter。Docverter是具有HTTP接口的文档转换服务器,为此使用了Pandoc。

import requests
r = requests.post(url='http://c.docverter.com/convert',
                  data={'to':'rst','from':'markdown'},
                  files={'input_files[]':open('README.md','rb')})
if r.ok:
    print r.content

For my requirements I didn’t want to install Pandoc in my computer. I used docverter. Docverter is a document conversion server with an HTTP interface using Pandoc for this.

import requests
r = requests.post(url='http://c.docverter.com/convert',
                  data={'to':'rst','from':'markdown'},
                  files={'input_files[]':open('README.md','rb')})
if r.ok:
    print r.content

回答 5

您可能还对以下事实感兴趣:可以编写一个公共子集,以便在以markdown呈现或以reStructuredText呈现时,文档以相同的方式出现:https: //gist.github.com/dupuy/1855764☺

You might also be interested in the fact that it is possible to write in a common subset so that your document comes out the same way when rendered as markdown or rendered as reStructuredText: https://gist.github.com/dupuy/1855764


回答 6

我遇到了这个问题,并使用以下两个bash脚本解决了这个问题。

请注意,我已将LaTeX捆绑到Markdown中。

#!/usr/bin/env bash

if [ $# -lt 1 ]; then
  echo "$0 file.md"
  exit;
fi

filename=$(basename "$1")
extension="${filename##*.}"
filename="${filename%.*}"

if [ "$extension" = "md" ]; then
  rst=".rst"
  pandoc $1 -o $filename$rst
fi

将其转换为html也很有用。md2html:

#!/usr/bin/env bash

if [ $# -lt 1 ]; then
  echo "$0 file.md <style.css>"
  exit;
fi

filename=$(basename "$1")
extension="${filename##*.}"
filename="${filename%.*}"

if [ "$extension" = "md" ]; then
  html=".html"
  if [ -z $2 ]; then
    # if no css
    pandoc -s -S --mathjax --highlight-style pygments $1 -o $filename$html
  else
    pandoc -s -S --mathjax --highlight-style pygments -c $2 $1 -o $filename$html
  fi
fi

希望对您有所帮助

I ran into this problem and solved it with the two following bash scripts.

Note that I have LaTeX bundled into my Markdown.

#!/usr/bin/env bash

if [ $# -lt 1 ]; then
  echo "$0 file.md"
  exit;
fi

filename=$(basename "$1")
extension="${filename##*.}"
filename="${filename%.*}"

if [ "$extension" = "md" ]; then
  rst=".rst"
  pandoc $1 -o $filename$rst
fi

Its also useful to convert to html. md2html:

#!/usr/bin/env bash

if [ $# -lt 1 ]; then
  echo "$0 file.md <style.css>"
  exit;
fi

filename=$(basename "$1")
extension="${filename##*.}"
filename="${filename%.*}"

if [ "$extension" = "md" ]; then
  html=".html"
  if [ -z $2 ]; then
    # if no css
    pandoc -s -S --mathjax --highlight-style pygments $1 -o $filename$html
  else
    pandoc -s -S --mathjax --highlight-style pygments -c $2 $1 -o $filename$html
  fi
fi

I hope that helps


回答 7

使用pandoc其他人建议的工具,我创建了一个md2rst实用程序来创建rst文件。即使此解决方案意味着您同时拥有an md和an,rst但它似乎是侵入性最小的,并且将允许将来添加任何降价支持。与更改相比setup.py,我更喜欢它,也许您也会:

#!/usr/bin/env python

'''
Recursively and destructively creates a .rst file for all Markdown
files in the target directory and below.

Created to deal with PyPa without changing anything in setup based on
the idea that getting proper Markdown support later is worth waiting
for rather than forcing a pandoc dependency in sample packages and such.

Vote for
(https://bitbucket.org/pypa/pypi/issue/148/support-markdown-for-readmes)

'''

import sys, os, re

markdown_sufs = ('.md','.markdown','.mkd')
markdown_regx = '\.(md|markdown|mkd)$'

target = '.'
if len(sys.argv) >= 2: target = sys.argv[1]

md_files = []
for root, dirnames, filenames in os.walk(target):
    for name in filenames:
        if name.endswith(markdown_sufs):
            md_files.append(os.path.join(root, name))

for md in md_files:
    bare = re.sub(markdown_regx,'',md)
    cmd='pandoc --from=markdown --to=rst "{}" -o "{}.rst"'
    print(cmd.format(md,bare))
    os.system(cmd.format(md,bare))

Using the pandoc tool suggested by others I created a md2rst utility to create the rst files. Even though this solution means you have both an md and an rst it seemed to be the least invasive and would allow for whatever future markdown support is added. I prefer it over altering setup.py and maybe you would as well:

#!/usr/bin/env python

'''
Recursively and destructively creates a .rst file for all Markdown
files in the target directory and below.

Created to deal with PyPa without changing anything in setup based on
the idea that getting proper Markdown support later is worth waiting
for rather than forcing a pandoc dependency in sample packages and such.

Vote for
(https://bitbucket.org/pypa/pypi/issue/148/support-markdown-for-readmes)

'''

import sys, os, re

markdown_sufs = ('.md','.markdown','.mkd')
markdown_regx = '\.(md|markdown|mkd)$'

target = '.'
if len(sys.argv) >= 2: target = sys.argv[1]

md_files = []
for root, dirnames, filenames in os.walk(target):
    for name in filenames:
        if name.endswith(markdown_sufs):
            md_files.append(os.path.join(root, name))

for md in md_files:
    bare = re.sub(markdown_regx,'',md)
    cmd='pandoc --from=markdown --to=rst "{}" -o "{}.rst"'
    print(cmd.format(md,bare))
    os.system(cmd.format(md,bare))

Conda:直接从github安装/升级

问题:Conda:直接从github安装/升级

我可以使用conda从GitHub安装/升级软件包吗?

例如,pip我可以这样做:

pip install git+git://github.com/scrappy/scrappy@master

scrappy直接从masterGitHub中的分支安装。我可以用conda做一些等效的事情吗?

如果这不可能,那么用conda安装pip并使用pip管理此类本地安装是否有意义?

Can I install/upgrade packages from GitHub using conda?

For example, with pip I can do:

pip install git+git://github.com/scrappy/scrappy@master

to install scrappy directly from the master branch in GitHub. Can I do something equivalent with conda?

If this is not possible, would it make any sense to install pip with conda and manage such local installations with pip?


回答 0

现在,对此有了更好的支持conda-env。例如,您现在可以执行以下操作:

name: sample_env
channels:
dependencies:
   - requests
   - bokeh>=0.10.0
   - pip:
     - "--editable=git+https://github.com/pythonforfacebook/facebook-sdk.git@8c0d34291aaafec00e02eaa71cc2a242790a0fcc#egg=facebook_sdk-master"

它仍然在后台调用pip,但是您现在可以在一个environment.yml文件中统一conda和pip软件包的规范。

如果要使用此文件更新根环境,则需要将其保存到文件中(例如environment.yml),然后运行命令:conda env update -f environment.yml

您更可能想创建一个新环境:

conda env create -f environment.yml (已按评论中的假设进行了更改)

There’s better support for this now through conda-env. You can, for example, now do:

name: sample_env
channels:
dependencies:
   - requests
   - bokeh>=0.10.0
   - pip:
     - "--editable=git+https://github.com/pythonforfacebook/facebook-sdk.git@8c0d34291aaafec00e02eaa71cc2a242790a0fcc#egg=facebook_sdk-master"

It’s still calling pip under the covers, but you can now unify your conda and pip package specifications in a single environment.yml file.

If you wanted to update your root environment with this file, you would need to save this to a file (for example, environment.yml), then run the command: conda env update -f environment.yml.

It’s more likely that you would want to create a new environment:

conda env create -f environment.yml (changed as supposed in the comments)


回答 1

答案已经过时了。您只需要conda安装pip和git。然后您可以正常使用pip:

  1. 激活您的conda环境 source activate myenv

  2. conda install git pip

  3. pip install git+git://github.com/scrappy/scrappy@master

The answers are outdated. You simply have to conda install pip and git. Then you can use pip normally:

  1. Activate your conda environment source activate myenv

  2. conda install git pip

  3. pip install git+git://github.com/scrappy/scrappy@master


回答 2

conda不直接支持此功能,因为它是从二进制文件安装的,而git install是从源代码安装的。conda build确实支持从git构建的配方。另一方面,如果您要做的只是保持最新和最新的软件包,则在Anaconda中使用pip很好,或者替代地,setup.py develop对git克隆使用。

conda doesn’t support this directly because it installs from binaries, whereas git install would be from source. conda build does support recipes that are built from git. On the other hand, if all you want to do is keep up-to-date with the latest and greatest of a package, using pip inside of Anaconda is just fine, or alternately, use setup.py develop against a git clone.


回答 3

我在condas问题中找到了对此的参考。现在应该可以进行以下操作。

name: sample_env
channels:
dependencies:
   - requests
   - bokeh>=0.10.0
   - pip:
     - git+https://github.com/pythonforfacebook/facebook-sdk.git

I found a reference to this in condas issues. The following should now work.

name: sample_env
channels:
dependencies:
   - requests
   - bokeh>=0.10.0
   - pip:
     - git+https://github.com/pythonforfacebook/facebook-sdk.git

为什么会看到“ TypeError:字符串索引必须为整数”?

问题:为什么会看到“ TypeError:字符串索引必须为整数”?

我正在学习python并试图将github问题转换为可读形式。使用有关如何将JSON转换为CSV的建议?我想出了这个:

import json
import csv

f=open('issues.json')
data = json.load(f)
f.close()

f=open("issues.csv","wb+")
csv_file=csv.writer(f)

csv_file.writerow(["gravatar_id","position","number","votes","created_at","comments","body","title","updated_at","html_url","user","labels","state"])

for item in data:
        csv_file.writerow([item["gravatar_id"], item["position"], item["number"], item["votes"], item["created_at"], item["comments"], item["body"], item["title"], item["updated_at"], item["html_url"], item["user"], item["labels"], item["state"]])

其中“ issues.json”是包含我的github问题的json文件。当我尝试运行它时,我得到

File "foo.py", line 14, in <module>
csv_file.writerow([item["gravatar_id"], item["position"], item["number"], item["votes"], item["created_at"], item["comments"], item["body"], item["title"], item["updated_at"], item["html_url"], item["user"], item["labels"], item["state"]])

TypeError: string indices must be integers

我在这里想念什么?哪些是“字符串索引”?我确定一旦完成这项工作,我还会遇到更多问题,但是就目前而言,我只是希望它能正常工作!

当我将for陈述调整为

for item in data:
    print item

我得到的是…“问题”-所以我在做一些更基本的错误。这是我的json:

{"issues":[{"gravatar_id":"44230311a3dcd684b6c5f81bf2ec9f60","position":2.0,"number":263,"votes":0,"created_at":"2010/09/17 16:06:50 -0700","comments":11,"body":"Add missing paging (Older>>) links...

当我打印时data,看起来真的很奇怪:

{u'issues': [{u'body': u'Add missing paging (Older>>) lin...

I’m playing with both learning python and trying to get github issues into a readable form. Using the advice on How can I convert JSON to CSV? I came up with this:

import json
import csv

f=open('issues.json')
data = json.load(f)
f.close()

f=open("issues.csv","wb+")
csv_file=csv.writer(f)

csv_file.writerow(["gravatar_id","position","number","votes","created_at","comments","body","title","updated_at","html_url","user","labels","state"])

for item in data:
        csv_file.writerow([item["gravatar_id"], item["position"], item["number"], item["votes"], item["created_at"], item["comments"], item["body"], item["title"], item["updated_at"], item["html_url"], item["user"], item["labels"], item["state"]])

Where “issues.json” is the json file containing my github issues. When I try to run that, I get

File "foo.py", line 14, in <module>
csv_file.writerow([item["gravatar_id"], item["position"], item["number"], item["votes"], item["created_at"], item["comments"], item["body"], item["title"], item["updated_at"], item["html_url"], item["user"], item["labels"], item["state"]])

TypeError: string indices must be integers

What am I missing here? Which are the “string indices”? I’m sure that once I get this working I’ll have more issues, but for now , I’d just love for this to work!

When I tweak the for statement to simply

for item in data:
    print item

what I get is … “issues” — so I’m doing something more basic wrong. Here’s a bit of my json:

{"issues":[{"gravatar_id":"44230311a3dcd684b6c5f81bf2ec9f60","position":2.0,"number":263,"votes":0,"created_at":"2010/09/17 16:06:50 -0700","comments":11,"body":"Add missing paging (Older>>) links...

when I print data it looks like it is getting munged really oddly:

{u'issues': [{u'body': u'Add missing paging (Older>>) lin...

回答 0

item您的代码中很可能是字符串;字符串索引是方括号中的那些,例如gravatar_id。因此,我首先要检查您的data变量以查看您在那里收到了什么;我猜这data是一个字符串列表(或至少一个包含至少一个字符串的列表),而它应该是字典列表。

item is most likely a string in your code; the string indices are the ones in the square brackets, e.g., gravatar_id. So I’d first check your data variable to see what you received there; I guess that data is a list of strings (or at least a list containing at least one string) while it should be a list of dictionaries.


回答 1

该变量item是一个字符串。索引如下所示:

>>> mystring = 'helloworld'
>>> print mystring[0]
'h'

上面的示例使用0字符串的索引来引用第一个字符。

字符串不能具有字符串索引(就像字典一样)。所以这行不通:

>>> mystring = 'helloworld'
>>> print mystring['stringindex']
TypeError: string indices must be integers

The variable item is a string. An index looks like this:

>>> mystring = 'helloworld'
>>> print mystring[0]
'h'

The above example uses the 0 index of the string to refer to the first character.

Strings can’t have string indices (like dictionaries can). So this won’t work:

>>> mystring = 'helloworld'
>>> print mystring['stringindex']
TypeError: string indices must be integers

回答 2

data是一个dict对象。因此,像这样迭代它:

Python 2

for key, value in data.iteritems():
    print key, value

Python 3

for key, value in data.items():
    print(key, value)

data is a dict object. So, iterate over it like this:

Python 2

for key, value in data.iteritems():
    print key, value

Python 3

for key, value in data.items():
    print(key, value)

回答 3

切片符号的TypeError str[a:b]

tl; dr:在两个索引之间和中使用冒号 :而不是逗号abstr[a:b]


使用字符串切片表示法常见的序列操作)时,可能会TypeError引发a 的增加,指出索引必须是整数,即使它们显然是整数。

>>> my_string = "hello world"
>>> my_string[0,5]
TypeError: string indices must be integers

我们显然将两个整数作为索引传递给切片符号,对吗?那么这是什么问题呢?

该错误可能非常令人沮丧-尤其是在学习Python初期-因为错误消息有点误导。

说明

调用时,我们隐式地将两个整数(0和5)的元组传递给切片符号,my_string[0,5]因为0,5(即使没有括号)求值结果也与该元组相同(0,5)

,实际上,逗号足以使Python将某些内容评估为元组:

>>> my_variable = 0,
>>> type(my_variable)
<class 'tuple'>

因此,我们这次在这里做了什么:

>>> my_string = "hello world"
>>> my_tuple = 0, 5
>>> my_string[my_tuple]
TypeError: string indices must be integers

现在,至少,该错误消息有意义。

我们需要用冒号替换逗号 ,,以正确分隔两个整数: :

>>> my_string = "hello world"
>>> my_string[0:5]
'hello'

更清晰,更有用的错误消息可能是:

TypeError: string indices must be integers (not tuple)

一条良好的错误消息会直接向用户显示他们的错误行为,而解决问题的方式将更加明显。

[因此,下次当您发现自己负责编写错误描述消息时,请考虑以下示例,并在错误消息中添加原因或其他有用的信息,以使您甚至其他人可以理解出了什么问题。

得到教训

  • 切片符号使用冒号:分隔其索引(以及步进范围,例如str[from:to:step]
  • 元组由逗号定义,(例如t = 1,
  • 在错误消息中添加一些信息,以使用户了解出了什么问题

欢呼和快乐编程
winklerrr


[我知道这个问题已经回答了,这不完全是线程启动程序提出的问题,但是由于上述问题导致出现相同的错误消息,所以我来到这里。至少我花了很多时间才找到那个小错字。

因此,我希望这会帮助那些偶然发现相同错误的人,并节省他们发现细微错误的时间。

TypeError for Slice Notation str[a:b]

tl;dr: use a colon : instead of a comma in between the two indices a and b in str[a:b]


When working with strings and slice notation (a common sequence operation), it can happen that a TypeError is raised, pointing out that the indices must be integers, even if they obviously are.

Example

>>> my_string = "hello world"
>>> my_string[0,5]
TypeError: string indices must be integers

We obviously passed two integers for the indices to the slice notation, right? So what is the problem here?

This error can be very frustrating – especially at the beginning of learning Python – because the error message is a little bit misleading.

Explanation

We implicitly passed a tuple of two integers (0 and 5) to the slice notation when we called my_string[0,5] because 0,5 (even without the parentheses) evaluates to the same tuple as (0,5) would do.

A comma , is actually enough for Python to evaluate something as a tuple:

>>> my_variable = 0,
>>> type(my_variable)
<class 'tuple'>

So what we did there, this time explicitly:

>>> my_string = "hello world"
>>> my_tuple = 0, 5
>>> my_string[my_tuple]
TypeError: string indices must be integers

Now, at least, the error message makes sense.

Solution

We need to replace the comma , with a colon : to separate the two integers correctly:

>>> my_string = "hello world"
>>> my_string[0:5]
'hello'

A clearer and more helpful error message could have been something like:

TypeError: string indices must be integers (not tuple)

A good error message shows the user directly what they did wrong and it would have been more obvious how to solve the problem.

[So the next time when you find yourself responsible for writing an error description message, think of this example and add the reason or other useful information to error message to let you and maybe other people understand what went wrong.]

Lessons learned

  • slice notation uses colons : to separate its indices (and step range, e.g. str[from:to:step])
  • tuples are defined by commas , (e.g. t = 1,)
  • add some information to error messages for users to understand what went wrong

Cheers and happy programming
winklerrr


[I know this question was already answered and this wasn’t exactly the question the thread starter asked, but I came here because of the above problem which leads to the same error message. At least it took me quite some time to find that little typo.

So I hope that this will help someone else who stumbled upon the same error and saves them some time finding that tiny mistake.]


回答 4

如果缺少逗号,可能会发生这种情况。当我有一个包含两个元组的列表时,我遇到了它,每个列表中的第一个位置包含一个字符串,第二个位置包含一个字符串。在一种情况下,我错误地省略了元组的第一部分之后的逗号,并且解释器认为我正在尝试索引第一部分。

This can happen if a comma is missing. I ran into it when I had a list of two-tuples, each of which consisted of a string in the first position, and a list in the second. I erroneously omitted the comma after the first component of a tuple in one case, and the interpreter thought I was trying to index the first component.


回答 5

我在Pandas上遇到过类似的问题,您需要使用iterrows()函数来遍历Pandas数据集Pandas文档以进行迭代

data = pd.read_csv('foo.csv')
for index,item in data.iterrows():
    print('{} {}'.format(item["gravatar_id"], item["position"]))

请注意,您需要处理该函数还返回的数据集中的索引。

I had a similar issue with Pandas, you need to use the iterrows() function to iterate through a Pandas dataset Pandas documentation for iterrows

data = pd.read_csv('foo.csv')
for index,item in data.iterrows():
    print('{} {}'.format(item["gravatar_id"], item["position"]))

note that you need to handle the index in the dataset that is also returned by the function.


是否可以使用pip从私有GitHub存储库安装软件包?

问题:是否可以使用pip从私有GitHub存储库安装软件包?

我正在尝试从私有GitHub存储库安装Python软件包。对于公共存储库,我可以发出以下正常运行的命令:

pip install git+git://github.com/django/django.git

但是,如果我尝试将其用于私有存储库:

pip install git+git://github.com/echweb/echweb-utils.git

我得到以下输出:

Downloading/unpacking git+git://github.com/echweb/echweb-utils.git
Cloning Git repository git://github.com/echweb/echweb-utils.git to /var/folders/cB/cB85g9P7HM4jcPn7nrvWRU+++TI/-Tmp-/pip-VRsIoo-build
Complete output from command /usr/local/bin/git clone git://github.com/echweb/echweb-utils.git /var/folders/cB/cB85g9P7HM4jcPn7nrvWRU+++TI/-Tmp-/pip-VRsIoo-build:
fatal: The remote end hung up unexpectedly

Cloning into /var/folders/cB/cB85g9P7HM4jcPn7nrvWRU+++TI/-Tmp-/pip-VRsIoo-build...

----------------------------------------
Command /usr/local/bin/git clone git://github.com/echweb/echweb-utils.git /var/folders/cB/cB85g9P7HM4jcPn7nrvWRU+++TI/-Tmp-/pip-VRsIoo-build failed with error code 128

我猜这是因为我试图在不提供任何身份验证的情况下访问私有存储库。因此,我尝试使用Git + ssh希望pip使用我的SSH公钥进行身份验证:

pip install git+ssh://github.com/echweb/echweb-utils.git

这给出以下输出:

Downloading/unpacking git+ssh://github.com/echweb/echweb-utils.git
Cloning Git repository ssh://github.com/echweb/echweb-utils.git to /var/folders/cB/cB85g9P7HM4jcPn7nrvWRU+++TI/-Tmp-/pip-DQB8s4-build
Complete output from command /usr/local/bin/git clone ssh://github.com/echweb/echweb-utils.git /var/folders/cB/cB85g9P7HM4jcPn7nrvWRU+++TI/-Tmp-/pip-DQB8s4-build:
Cloning into /var/folders/cB/cB85g9P7HM4jcPn7nrvWRU+++TI/-Tmp-/pip-DQB8s4-build...

Permission denied (publickey).

fatal: The remote end hung up unexpectedly

----------------------------------------
Command /usr/local/bin/git clone ssh://github.com/echweb/echweb-utils.git /var/folders/cB/cB85g9P7HM4jcPn7nrvWRU+++TI/-Tmp-/pip-DQB8s4-build failed with error code 128

我正在努力实现的目标是否可能?如果是这样,我该怎么办?

I am trying to install a Python package from a private GitHub repository. For a public repository, I can issue the following command which works fine:

pip install git+git://github.com/django/django.git

However, if I try this for a private repository:

pip install git+git://github.com/echweb/echweb-utils.git

I get the following output:

Downloading/unpacking git+git://github.com/echweb/echweb-utils.git
Cloning Git repository git://github.com/echweb/echweb-utils.git to /var/folders/cB/cB85g9P7HM4jcPn7nrvWRU+++TI/-Tmp-/pip-VRsIoo-build
Complete output from command /usr/local/bin/git clone git://github.com/echweb/echweb-utils.git /var/folders/cB/cB85g9P7HM4jcPn7nrvWRU+++TI/-Tmp-/pip-VRsIoo-build:
fatal: The remote end hung up unexpectedly

Cloning into /var/folders/cB/cB85g9P7HM4jcPn7nrvWRU+++TI/-Tmp-/pip-VRsIoo-build...

----------------------------------------
Command /usr/local/bin/git clone git://github.com/echweb/echweb-utils.git /var/folders/cB/cB85g9P7HM4jcPn7nrvWRU+++TI/-Tmp-/pip-VRsIoo-build failed with error code 128

I guess this is because I am trying to access a private repository without providing any authentication. I therefore tried to use Git + ssh hoping that pip would use my SSH public key to authenticate:

pip install git+ssh://github.com/echweb/echweb-utils.git

This gives the following output:

Downloading/unpacking git+ssh://github.com/echweb/echweb-utils.git
Cloning Git repository ssh://github.com/echweb/echweb-utils.git to /var/folders/cB/cB85g9P7HM4jcPn7nrvWRU+++TI/-Tmp-/pip-DQB8s4-build
Complete output from command /usr/local/bin/git clone ssh://github.com/echweb/echweb-utils.git /var/folders/cB/cB85g9P7HM4jcPn7nrvWRU+++TI/-Tmp-/pip-DQB8s4-build:
Cloning into /var/folders/cB/cB85g9P7HM4jcPn7nrvWRU+++TI/-Tmp-/pip-DQB8s4-build...

Permission denied (publickey).

fatal: The remote end hung up unexpectedly

----------------------------------------
Command /usr/local/bin/git clone ssh://github.com/echweb/echweb-utils.git /var/folders/cB/cB85g9P7HM4jcPn7nrvWRU+++TI/-Tmp-/pip-DQB8s4-build failed with error code 128

Is what I am trying to achieve even possible? If so, how can I do it?


回答 0

您可以使用git+sshURI方案,但是必须设置用户名:

pip install git+ssh://git@github.com/echweb/echweb-utils.git

git@在URI中看到该部分了吗?

PS:另请参阅有关部署密钥

PPS:在我的安装中,“ git + ssh” URI方案仅适用于“可编辑”的要求:

pip install -e URI#egg=EggName

切记:在命令中使用遥控器的地址之前:,请将要git remote -v打印的/字符更改为字符pip

$ git remote -v
origin  git@github.com:echweb/echweb-utils.git (fetch)
                      ^ change this to a '/' character

如果您忘记了,则会收到此错误:

ssh: Could not resolve hostname github.com:echweb:
         nodename nor servname provided, or not known

You can use the git+ssh URI scheme, but you must set a username:

pip install git+ssh://git@github.com/echweb/echweb-utils.git

Do you see the git@ part into the URI?

PS: Also read about deploy keys.

PPS: In my installation, the “git+ssh” URI scheme works only with “editable” requirements:

pip install -e URI#egg=EggName

Remember: Change the : character that git remote -v prints to a / character before using the remote’s address in the pip command:

$ git remote -v
origin  git@github.com:echweb/echweb-utils.git (fetch)
                      ^ change this to a '/' character

If you forget, you will get this error:

ssh: Could not resolve hostname github.com:echweb:
         nodename nor servname provided, or not known

回答 1

作为另一项技术,如果您在本地克隆了专用存储库,则可以执行以下操作:

pip install git+file://c:/repo/directory

更现代的是,您可以执行此操作(这-e将意味着您不必在更改被反映之前就提交更改):

pip install -e C:\repo\directory

As an additional technique, if you have the private repository cloned locally, you can do:

pip install git+file://c:/repo/directory

More modernly, you can just do this (and the -e will mean you don’t have to commit changes before they’re reflected):

pip install -e C:\repo\directory

回答 2

您可以使用HTTPS URL直接执行此操作,如下所示:

pip install git+https://github.com/username/repo.git

例如,这也可以仅将这一行添加到Django项目中的requirements.txt中。

You can do it directly with the HTTPS URL like this:

pip install git+https://github.com/username/repo.git

This also works just appending that line in the requirements.txt in a Django project, for instance.


回答 3

它也可以与Bitbucket一起使用

pip install git+ssh://git@bitbucket.org/username/projectname.git

在这种情况下,Pip将使用您的SSH密钥。

It also works with Bitbucket:

pip install git+ssh://git@bitbucket.org/username/projectname.git

Pip will use your SSH keys in this case.


回答 4

需求文件的语法在此处给出:

https://pip.pypa.io/zh_CN/latest/reference/pip_install.html#requirements-file-format

因此,例如,使用:

-e git+http://github.com/rwillmer/django-behave#egg=django-behave

如果您希望源在安装后继续存在。

要不就

git+http://github.com/rwillmer/django-behave#egg=django-behave

如果您只想安装它。

The syntax for the requirements file is given here:

https://pip.pypa.io/en/latest/reference/pip_install.html#requirements-file-format

So for example, use:

-e git+http://github.com/rwillmer/django-behave#egg=django-behave

if you want the source to stick around after installation.

Or just

git+http://github.com/rwillmer/django-behave#egg=django-behave

if you just want it to be installed.


回答 5

我发现使用令牌比使用SSH密钥容易得多。我在这方面找不到很多好的文档,因此我主要是通过反复试验来遇到此解决方案。此外,从pip和setuptools安装有一些细微的差异。但是这种方式对两者都适用。

GitHub尚未提供(目前,截至2016年8月)提供了一种获取私有存储库zip / tarball的简便方法。因此,您需要指向setuptools来告诉setuptools您指向的是Git存储库:

from setuptools import setup
import os
# Get the deploy key from https://help.github.com/articles/git-automation-with-oauth-tokens/
github_token = os.environ['GITHUB_TOKEN']

setup(
    # ...
    install_requires='package',
    dependency_links = [
    'git+https://{github_token}@github.com/user/{package}.git/@{version}#egg={package}-0'
        .format(github_token=github_token, package=package, version=master)
        ]

这里有几点注意事项:

  • 对于私有存储库,您需要通过GitHub进行身份验证;我发现的最简单的方法是创建OAuth令牌,将其放入您的环境中,然后将其包含在URL中
  • 即使在PyPI上没有任何软件包,您也需要在链接末尾包含一些版本号(在此处0)。这必须是实际数字,而不是单词。
  • 您需要以 git+序号告诉setuptools它是克隆存储库,而不是指向zip / tarball
  • version 可以是分支,标签或提交哈希
  • --process-dependency-links如果从pip安装,则需要提供

I found it much easier to use tokens than SSH keys. I couldn’t find much good documentation on this, so I came across this solution mainly through trial and error. Further, installing from pip and setuptools have some subtle differences; but this way should work for both.

GitHub don’t (currently, as of August 2016) offer an easy way to get the zip / tarball of private repositories. So you need to point setuptools to tell setuptools that you’re pointing to a Git repository:

from setuptools import setup
import os
# Get the deploy key from https://help.github.com/articles/git-automation-with-oauth-tokens/
github_token = os.environ['GITHUB_TOKEN']

setup(
    # ...
    install_requires='package',
    dependency_links = [
    'git+https://{github_token}@github.com/user/{package}.git/@{version}#egg={package}-0'
        .format(github_token=github_token, package=package, version=master)
        ]

A couple of notes here:

  • For private repositories, you need to authenticate with GitHub; the simplest way I found is to create an OAuth token, drop that into your environment, and then include it with the URL
  • You need to include some version number (here is 0) at the end of the link, even if there’s isn’t any package on PyPI. This has to be a actual number, not a word.
  • You need to preface with git+ to tell setuptools it’s to clone the repository, rather than pointing at a zip / tarball
  • version can be a branch, a tag, or a commit hash
  • You need to supply --process-dependency-links if installing from pip

回答 6

我想出了一种自动“点安装”不需要密码提示的GitLab私有存储库的方法。这种方法使用GitLab“部署密钥”和SSH配置文件,因此您可以使用个人SSH密钥以外的其他密钥进行部署(在我的情况下,由“机器人”使用)。也许有人会使用GitHub进行验证。

创建一个新的SSH密钥:

ssh-keygen -t rsa -C "GitLab_Robot_Deploy_Key"

该文件应显示为~/.ssh/GitLab_Robot_Deploy_Key~/.ssh/GitLab_Robot_Deploy_Key.pub

~/.ssh/GitLab_Robot_Deploy_Key.pub文件的内容复制并粘贴到GitLab的“部署密钥”对话框中。

测试新的部署密钥

以下命令告诉SSH使用新的部署密钥来建立连接。成功后,您将收到消息:“欢迎使用GitLab,用户名!”

ssh -T -i ~/.ssh/GitLab_Robot_Deploy_Key git@gitlab.mycorp.com

创建SSH配置文件

接下来,使用编辑器创建~/.ssh/config文件。添加以下内容。“主机”值可以是您想要的任何值(请记住它,因为稍后会使用它)。HostName是您的GitLab实例的URL。IdentifyFile是您在第一步中创建的SSH密钥文件的路径。

Host GitLab
  HostName gitlab.mycorp.com
  IdentityFile ~/.ssh/GitLab_Robot_Deploy_Key

将SSH指向配置文件

oxyum为我们提供了通过SSH使用pip的方法:

pip install git+ssh://git@gitlab.mycorp.com/my_name/my_repo.git

我们只需要对其稍作修改即可使SSH使用我们的新Deploy Key。为此,我们将SSH指向SSH配置文件中的Host条目。只需将命令中的“ gitlab.mycorp.com”替换为我们在SSH配置文件中使用的主机名即可:

pip install git+ssh://git@GitLab/my_name/my_repo.git

该软件包现在应该安装,没有任何密码提示。

参考文献A
参考文献B

I figured out a way to automagically ‘pip install’ a GitLab private repository that requires no password prompt. This approach uses GitLab “Deploy Keys” and an SSH configuration file, so you can deploy using keys other than your personal SSH keys (in my case, for use by a ‘bot). Perhaps someone kind soul can verify using GitHub.

Create a New SSH key:

ssh-keygen -t rsa -C "GitLab_Robot_Deploy_Key"

The file should show up as ~/.ssh/GitLab_Robot_Deploy_Key and ~/.ssh/GitLab_Robot_Deploy_Key.pub.

Copy and paste the contents of the ~/.ssh/GitLab_Robot_Deploy_Key.pub file into the GitLab “Deploy Keys” dialog.

Test the New Deploy Key

The following command tells SSH to use your new deploy key to set up the connection. On success, you should get the message: “Welcome to GitLab, UserName!”

ssh -T -i ~/.ssh/GitLab_Robot_Deploy_Key git@gitlab.mycorp.com

Create the SSH Configuration File

Next, use an editor to create a ~/.ssh/config file. Add the following contents. The ‘Host’ value can be anything you want (just remember it, because you’ll be using it later). The HostName is the URL to your GitLab instance. The IdentifyFile is path to the SSH key file you created in the first step.

Host GitLab
  HostName gitlab.mycorp.com
  IdentityFile ~/.ssh/GitLab_Robot_Deploy_Key

Point SSH to the Configuration file

oxyum gave us the recipe for using pip with SSH:

pip install git+ssh://git@gitlab.mycorp.com/my_name/my_repo.git

We just need to modify it a bit to make SSH use our new Deploy Key. We do that by pointing SSH to the Host entry in the SSH configuration file. Just replace the ‘gitlab.mycorp.com’ in the command to the host name we used in the SSH configuration file:

pip install git+ssh://git@GitLab/my_name/my_repo.git

The package should now install without any password prompt.

Reference A
Reference B


回答 7

从GitHub安装时,我可以使用:

pip install git+ssh://git@github.com/<username>/<projectname>.git#egg=<eggname>

但是,由于我必须以pip as身份运行sudo,所以SSH密钥不再可与GitHub一起使用,并且“ git clone”在“权限被拒绝(公共密钥)”上失败。使用git+https允许我以sudo的身份运行命令,并让GitHub询问我的用户名/密码。

sudo pip install git+https://github.com/<username>/<projectname>.git#egg=<eggname>

When I was installing from GitHub I was able to use:

pip install git+ssh://git@github.com/<username>/<projectname>.git#egg=<eggname>

But, since I had to run pip as sudo, the SSH keys were not working with GitHub any more, and “git clone” failed on “Permission denied (publickey)”. Using git+https allowed me to run the command as sudo, and have GitHub ask me for my user/password.

sudo pip install git+https://github.com/<username>/<projectname>.git#egg=<eggname>

回答 8

您还可以通过提供登录凭据(登录名和密码,或部署令牌)通过git + https://github.com / … URL 安装私有存储库依赖关系,以使用该文件卷曲.netrc

echo "machine github.com login ei-grad password mypasswordshouldbehere" > ~/.netrc
pip install "git+https://github.com/ei-grad/my_private_repo.git#egg=my_private_repo"

You can also install a private repository dependency via git+https://github.com/… URL by providing login credentials (login and password, or deploy token) for curl with the .netrc file:

echo "machine github.com login ei-grad password mypasswordshouldbehere" > ~/.netrc
pip install "git+https://github.com/ei-grad/my_private_repo.git#egg=my_private_repo"

回答 9

如果要从CI服务器等中的需求文件中安装依赖项,可以执行以下操作:

git config --global credential.helper 'cache'
echo "protocol=https
host=example.com
username=${GIT_USER}
password=${GIT_PASS}
" | git credential approve
pip install -r requirements.txt

就我而言,我使用GIT_USER=gitlab-ci-tokenGIT_PASS=${CI_JOB_TOKEN}

该方法具有明显的优势。您只有一个包含所有依赖项的需求文件。

If you want to install dependencies from a requirements file within a CI server or alike, you can do this:

git config --global credential.helper 'cache'
echo "protocol=https
host=example.com
username=${GIT_USER}
password=${GIT_PASS}
" | git credential approve
pip install -r requirements.txt

In my case, I used GIT_USER=gitlab-ci-token and GIT_PASS=${CI_JOB_TOKEN}.

This method has a clear advantage. You have a single requirements file which contains all of your dependencies.


回答 10

如果您不想使用SSH,则可以在HTTPS URL中添加用户名和密码。

下面的代码假定您在工作目录中有一个包含密码的名为“ pass”的文件。

export PASS=$(cat pass)
pip install git+https://<username>:$PASS@github.com/echweb/echweb-utils.git

If you don’t want to use SSH, you could add the username and password in the HTTPS URL.

The code below assumes that you have a file called “pass” in the working directory that contains your password.

export PASS=$(cat pass)
pip install git+https://<username>:$PASS@github.com/echweb/echweb-utils.git

回答 11

oxyum的解决方案可以解决此问题。我只想指出,如果您使用进行安装,则需要小心,sudo因为密钥也必须存储为root(例如,/root/.ssh)。

然后你可以输入

sudo pip install git+ssh://git@github.com/echweb/echweb-utils.git

oxyum’s solution is OK for this answer. I just want to point out that you need to be careful if you are installing using sudo as the keys must be stored for root too (for example, /root/.ssh).

Then you can type

sudo pip install git+ssh://git@github.com/echweb/echweb-utils.git

回答 12

如果您在GitHub,GitLab等上拥有自己的库/软件包,则必须添加一个标签以提交该库的具体版本,例如v2.0,然后可以安装软件包:

pip install git+ssh://link/name/repo.git@v2.0

这对我有用。其他解决方案对我不起作用。

If you have your own library/package on GitHub, GitLab, etc., you have to add a tag to commit with a concrete version of the library, for example, v2.0, and then you can install your package:

pip install git+ssh://link/name/repo.git@v2.0

This works for me. Other solutions haven’t worked for me.


回答 13

这是一种对我有用的快速方法。只需分叉存储库,并使用您自己的GitHub帐户进行安装即可

pip install git+https://github.com/yourName/repoName

Here’s a quick method that worked for me. Simply fork the repo and install it from your own GitHub account with

pip install git+https://github.com/yourName/repoName

回答 14

只需从原始git clone命令(或从git remote -v)复制遥控器。您将获得如下内容:

  • 位桶: git+ssh://git@bitbucket.org:your_account/my_pro.git

  • 的GitHub: git+ssh://git@github.com:your_account/my_pro.git

接下来,您需要替换:/旁边的域名。

因此,使用以下命令进行安装:

pip install git+ssh://git@bitbucket.org/your_account/my_pro.git

Just copy the remote from the original git clone command (or from git remote -v). You will get something like this:

  • Bitbucket: git+ssh://git@bitbucket.org:your_account/my_pro.git

  • GitHub: git+ssh://git@github.com:your_account/my_pro.git

Next, you need to replace : with / next to the domain name.

So install using:

pip install git+ssh://git@bitbucket.org/your_account/my_pro.git

回答 15

你可以试试

pip install git+git@gitlab.mycorp.com/my_name/my_repo.git

没有ssh:...。这对我行得通。

You may try

pip install git+git@gitlab.mycorp.com/my_name/my_repo.git

without ssh:.... That works for me.


如何在Requirements.txt中声明直接的github源

问题:如何在Requirements.txt中声明直接的github源

我已经使用以下命令安装了一个库

pip install git+git://github.com/mozilla/elasticutils.git

直接从Github存储库安装它。这工作正常,我想在我的requirements.txt。我看其他的票像这样但这并没有解决我的问题。如果我把像

-f git+git://github.com/mozilla/elasticutils.git
elasticutils==0.7.dev

requirements.txt文件中,pip install -r requirements.txt结果为以下输出:

Downloading/unpacking elasticutils==0.7.dev (from -r requirements.txt (line 20))
  Could not find a version that satisfies the requirement elasticutils==0.7.dev (from -r requirements.txt (line 20)) (from versions: )
No distributions matching the version for elasticutils==0.7.dev (from -r requirements.txt (line 20))

需求文件文档中没有提及使用git+git协议说明符的链接,因此也许只是不被支持。

有人能解决我的问题吗?

I’ve installed a library using the command

pip install git+git://github.com/mozilla/elasticutils.git

which installs it directly from a Github repository. This works fine and I want to have that dependency in my requirements.txt. I’ve looked at other tickets like this but that didn’t solve my problem. If I put something like

-f git+git://github.com/mozilla/elasticutils.git
elasticutils==0.7.dev

in the requirements.txt file, a pip install -r requirements.txt results in the following output:

Downloading/unpacking elasticutils==0.7.dev (from -r requirements.txt (line 20))
  Could not find a version that satisfies the requirement elasticutils==0.7.dev (from -r requirements.txt (line 20)) (from versions: )
No distributions matching the version for elasticutils==0.7.dev (from -r requirements.txt (line 20))

The documentation of the requirements file does not mention links using the git+git protocol specifier, so maybe this is just not supported.

Does anybody have a solution for my problem?


回答 0

“ Editable”包语法可用于requirements.txt从各种VCS(git,hg,bzr,svn)导入包:

-e git://github.com/mozilla/elasticutils.git#egg=elasticutils

另外,可以指向特定的提交:

-e git://github.com/mozilla/elasticutils.git@000b14389171a9f0d7d713466b32bc649b0bed8e#egg=elasticutils

“Editable” packages syntax can be used in requirements.txt to import packages from a variety of VCS (git, hg, bzr, svn):

-e git://github.com/mozilla/elasticutils.git#egg=elasticutils

Also, it is possible to point to particular commit:

-e git://github.com/mozilla/elasticutils.git@000b14389171a9f0d7d713466b32bc649b0bed8e#egg=elasticutils

回答 1

通常,您的requirements.txt文件如下所示:

package-one==1.9.4
package-two==3.7.1
package-three==1.0.1
...

要指定Github存储库,您不需要package-name==约定。

下面的示例更新 package-two使用GitHub存储库进行。@和之间的文字#表示包装的详细信息。

指定提交哈希(41b95ec在updated的上下文中requirements.txt):

package-one==1.9.4
git+git://github.com/path/to/package-two@41b95ec#egg=package-two
package-three==1.0.1

指定分支名称(master):

git+git://github.com/path/to/package-two@master#egg=package-two

指定标签(0.1):

git+git://github.com/path/to/package-two@0.1#egg=package-two

指定发布(3.7.1):

git+git://github.com/path/to/package-two@releases/tag/v3.7.1#egg=package-two

请注意,#egg=package-two此处不是注释,而是要明确说明软件包名称

这篇博客文章对此主题进行了更多讨论。

Normally your requirements.txt file would look something like this:

package-one==1.9.4
package-two==3.7.1
package-three==1.0.1
...

To specify a Github repo, you do not need the package-name== convention.

The examples below update package-two using a GitHub repo. The text between @ and # denotes the specifics of the package.

Specify commit hash (41b95ec in the context of updated requirements.txt):

package-one==1.9.4
git+git://github.com/path/to/package-two@41b95ec#egg=package-two
package-three==1.0.1

Specify branch name (master):

git+git://github.com/path/to/package-two@master#egg=package-two

Specify tag (0.1):

git+git://github.com/path/to/package-two@0.1#egg=package-two

Specify release (3.7.1):

git+git://github.com/path/to/package-two@releases/tag/v3.7.1#egg=package-two

Note that #egg=package-two is not a comment here, it is to explicitly state the package name

This blog post has some more discussion on the topic.


回答 2

requirements.txt从pip 7.0开始,可以通过以下方式指定对git存储库中软件包的依赖关系:1

[-e] git+git://git.myproject.org/SomeProject#egg=SomeProject
[-e] git+https://git.myproject.org/SomeProject#egg=SomeProject
[-e] git+ssh://git.myproject.org/SomeProject#egg=SomeProject
-e git+git@git.myproject.org:SomeProject#egg=SomeProject

对于Github,这意味着您可以做到(请注意,省略了-e):

git+git://github.com/mozilla/elasticutils.git#egg=elasticutils

为什么要额外回答?
-e在其他答案中对标志有些困惑,所以这是我的澄清:

-e或” --editable标志表示包装已安装在<venv path>/src/SomeProject深处,因此不会放入深处<venv path>/lib/pythonX.X/site-packages/SomeProject。否则,它将被放置在其中。2

文献资料

requirements.txt allows the following ways of specifying a dependency on a package in a git repository as of pip 7.0:1

[-e] git+git://git.myproject.org/SomeProject#egg=SomeProject
[-e] git+https://git.myproject.org/SomeProject#egg=SomeProject
[-e] git+ssh://git.myproject.org/SomeProject#egg=SomeProject
-e git+git@git.myproject.org:SomeProject#egg=SomeProject

For Github that means you can do (notice the omitted -e):

git+git://github.com/mozilla/elasticutils.git#egg=elasticutils

Why the extra answer?
I got somewhat confused by the -e flag in the other answers so here’s my clarification:

The -e or --editable flag means that the package is installed in <venv path>/src/SomeProject and thus not in the deeply buried <venv path>/lib/pythonX.X/site-packages/SomeProject it would otherwise be placed in.2

Documentation


回答 3

首先,以任何已知的方式使用git+git或安装git+https。安装项目kronok的分支的示例brabeion

pip install -e git+https://github.com/kronok/brabeion.git@12efe6aa06b85ae5ff725d3033e38f624e0a616f#egg=brabeion

其次,使用pip freeze > requirements.txt来获取正确的东西requirements.txt。在这种情况下,您将获得

-e git+https://github.com/kronok/brabeion.git@12efe6aa06b85ae5ff725d3033e38f624e0a616f#egg=brabeion-master

三,测试结果:

pip uninstall brabeion
pip install -r requirements.txt

First, install with git+git or git+https, in any way you know. Example of installing kronok‘s branch of the brabeion project:

pip install -e git+https://github.com/kronok/brabeion.git@12efe6aa06b85ae5ff725d3033e38f624e0a616f#egg=brabeion

Second, use pip freeze > requirements.txt to get the right thing in your requirements.txt. In this case, you will get

-e git+https://github.com/kronok/brabeion.git@12efe6aa06b85ae5ff725d3033e38f624e0a616f#egg=brabeion-master

Third, test the result:

pip uninstall brabeion
pip install -r requirements.txt

回答 4

由于pip v1.5(发布于2014年1月1日:CHANGELOGPR),您还可以指定git repo的子目录来包含您的模块。语法如下所示:

pip install -e git+https://git.repo/some_repo.git#egg=my_subdir_pkg&subdirectory=my_subdir_pkg # install a python package from a repo subdirectory

注意:作为pip模块的作者,如果可能的话,理想情况下,您可能希望将模块发布到它自己的顶级仓库中。但是,此功能对于某些子目录中包含python模块的现有存储库很有帮助。如果它们也没有发布到pypi,则可能会被迫以这种方式安装它们。

Since pip v1.5, (released Jan 1 2014: CHANGELOG, PR) you may also specify a subdirectory of a git repo to contain your module. The syntax looks like this:

pip install -e git+https://git.repo/some_repo.git#egg=my_subdir_pkg&subdirectory=my_subdir_pkg # install a python package from a repo subdirectory

Note: As a pip module author, ideally you’d probably want to publish your module in it’s own top-level repo if you can. Yet this feature is helpful for some pre-existing repos that contain python modules in subdirectories. You might be forced to install them this way if they are not published to pypi too.


回答 5

我发现要获取pip3(v9.0.1,由Ubuntu 18.04的软件包管理器安装)来实际安装我告诉它要安装的东西有点棘手。我发布此答案是为了节省遇到此问题的任何人的时间。

将其放入Requirements.txt文件失败:

git+git://github.com/myname/myrepo.git@my-branch#egg=eggname

“失败”是指当它从Git下载代码时,它最终安装了PyPi上找到的代码的原始版本,而不是该分支上存储库中的代码。

但是,安装commmit而不是分支名称是可行的:

git+git://github.com/myname/myrepo.git@d27d07c9e862feb939e56d0df19d5733ea7b4f4d#egg=eggname

I’m finding that it’s kind of tricky to get pip3 (v9.0.1, as installed by Ubuntu 18.04’s package manager) to actually install the thing I tell it to install. I’m posting this answer to save anyone’s time who runs into this problem.

Putting this into a requirements.txt file failed:

git+git://github.com/myname/myrepo.git@my-branch#egg=eggname

By “failed” I mean that while it downloaded the code from Git, it ended up installing the original version of the code, as found on PyPi, instead of the code in the repo on that branch.

However, installing the commmit instead of the branch name works:

git+git://github.com/myname/myrepo.git@d27d07c9e862feb939e56d0df19d5733ea7b4f4d#egg=eggname

Gitsome-增强型Git/GitHub命令行界面(CLI)。GitHub和GitHub企业的官方集成:https://github.com/works-with/category/desktop-tools

一个Official Integration对于GitHub和GitHub Enterprise

为什么gitsome

Git命令行

虽然标准的Git命令行是管理基于Git的repo的一个很好的工具,但是它可以很难记住这个用法地址为:

  • 150多个瓷器和管道命令
  • 无数特定于命令的选项
  • 标签和分支等资源

Git命令行不与GitHub集成,强制您在命令行和浏览器之间切换

gitsome-具有自动完成功能的增压Git/GitHub CLI

gitsome旨在通过专注于以下方面来增强您的标准git/shell界面:

  • 提高易用性
  • 提高工作效率

深度GitHub集成

并不是所有的GitHub工作流都能在终端中很好地工作;gitsome试图将目标对准那些这样做的人

gitsome包括29个与一起使用的GitHub集成命令ALL外壳:

$ gh <command> [param] [options]

gh命令以及Git-Extrashub解锁更多GitHub集成的命令!

带有交互式帮助的Git和GitHub自动完成程序

您可以运行可选壳牌:

 $ gitsome

要启用自动完成交互式帮助对于以下内容:

通用自动补全程序

gitsome自动完成以下内容:

  • Shell命令
  • 文件和目录
  • 环境变量
  • 手册页
  • python

要启用其他自动完成,请查看Enabling Bash Completions部分

鱼式自动建议

gitsome支持鱼式自动建议。使用right arrow完成建议的关键

Python REPL

gitsome由以下人员提供动力xonsh,它支持Python REPL

在shell命令旁边运行Python命令:

附加内容xonsh功能可在xonsh tutorial

命令历史记录

gitsome跟踪您输入的命令并将其存储在~/.xonsh_history.json使用向上和向下箭头键循环查看命令历史记录

可自定义的突出显示

可以控制用于突出显示的ansi颜色,方法是更新~/.gitsomeconfig文件

颜色选项包括:

'black', 'red', 'green', 'yellow',
'blue', 'magenta', 'cyan', 'white'

对于无颜色,请将值设置为Nonewhite在某些终端上可能显示为浅灰色

可用的平台

gitsome适用于Mac、Linux、Unix、Windows,以及Docker

待办事项

并不是所有的GitHub工作流都能在终端中很好地工作;gitsome试图将目标对准那些这样做的人

  • 添加其他GitHub API集成

gitsome才刚刚开始。请随意……contribute!

索引

GitHub集成命令

安装和测试

杂项

GitHub集成命令语法

用法:

$ gh <command> [param] [options]

GitHub集成命令列表

  configure            Configure gitsome.
  create-comment       Create a comment on the given issue.
  create-issue         Create an issue.
  create-repo          Create a repo.
  emails               List all the user's registered emails.
  emojis               List all GitHub supported emojis.
  feed                 List all activity for the given user or repo.
  followers            List all followers and the total follower count.
  following            List all followed users and the total followed count.
  gitignore-template   Output the gitignore template for the given language.
  gitignore-templates  Output all supported gitignore templates.
  issue                Output detailed information about the given issue.
  issues               List all issues matching the filter.
  license              Output the license template for the given license.
  licenses             Output all supported license templates.
  me                   List information about the logged in user.
  notifications        List all notifications.
  octo                 Output an Easter egg or the given message from Octocat.
  pull-request         Output detailed information about the given pull request.
  pull-requests        List all pull requests.
  rate-limit           Output the rate limit.  Not available for Enterprise.
  repo                 Output detailed information about the given filter.
  repos                List all repos matching the given filter.
  search-issues        Search for all issues matching the given query.
  search-repos         Search for all repos matching the given query.
  starred              Output starred repos.
  trending             List trending repos for the given language.
  user                 List information about the given user.
  view                 View the given index in the terminal or a browser.

GitHub集成命令参考:COMMANDS.md

请参阅GitHub Integration Commands Reference in COMMANDS.md对于详细讨论所有GitHub集成命令、参数、选项和示例

请查看下一节,了解快速参考

GitHub集成命令快速参考

配置gitsome

要与GitHub正确集成,您必须首先配置gitsome

$ gh configure

对于GitHub Enterprise用户,使用-e/--enterprise标志:

$ gh configure -e

列表源

列出您的新闻源

$ gh feed

列出用户的活动摘要

查看您的活动订阅源或其他用户的活动订阅源,也可以选择使用寻呼机-p/--pager这个pager option可用于许多命令

$ gh feed donnemartin -p

列出回购的活动提要

$ gh feed donnemartin/gitsome -p

列出通知

$ gh notifications

列出拉式请求

查看您的回购的所有拉式请求:

$ gh pull-requests

过滤问题

查看您提到的所有未决问题:

$ gh issues --issue_state open --issue_filter mentioned

查看所有问题,只筛选分配给您的问题,而不考虑状态(打开、关闭):

$ gh issues --issue_state all --issue_filter assigned

有关过滤和州限定词的更多信息,请访问gh issues参考位置COMMANDS.md

过滤星级报告

$ gh starred "repo filter"

搜索问题和报告

搜索问题

+1最多的搜索问题:

$ gh search-issues "is:open is:issue sort:reactions-+1-desc" -p

评论最多的搜索问题:

$ gh search-issues "is:open is:issue sort:comments-desc" -p

使用“需要帮助”标签搜索问题:

$ gh search-issues "is:open is:issue label:\"help wanted\"" -p

已标记您的用户名的搜索问题@donnemartin

$ gh search-issues "is:issue donnemartin is:open" -p

搜索您所有未解决的私人问题:

$ gh search-issues "is:open is:issue is:private" -p

有关查询限定符的更多信息,请访问searching issues reference

搜索报告

搜索2015年或之后创建的所有Python repos,>=1000星:

$ gh search-repos "created:>=2015-01-01 stars:>=1000 language:python" --sort stars -p

有关查询限定符的更多信息,请访问searching repos reference

列出趋势报告和开发人员

查看趋势回购:

$ gh trending [language] [-w/--weekly] [-m/--monthly] [-d/--devs] [-b/--browser]

查看趋势DEV(目前仅浏览器支持DEV):

$ gh trending [language] --devs --browser

查看内容

这个view命令

查看前面列出的通知、拉取请求、问题、回复、用户等,HTML格式适合您的终端,也可以选择在您的浏览器中查看:

$ gh view [#] [-b/--browser]

这个issue命令

查看问题:

$ gh issue donnemartin/saws/1

这个pull-request命令

查看拉取请求:

$ gh pull-request donnemartin/awesome-aws/2

设置.gitignore

列出所有可用的.gitignore模板:

$ gh gitignore-templates

设置您的.gitignore

$ gh gitignore-template Python > .gitignore

设置LICENSE

列出所有可用的LICENSE模板:

$ gh licenses

设置您的或LICENSE

$ gh license MIT > LICENSE

召唤十月猫

在十月猫那天打电话说出给定的信息或复活节彩蛋:

$ gh octo [say]

查看配置文件

查看用户的配置文件

$ gh user octocat

查看您的个人资料

使用查看您的个人资料gh user [YOUR_USER_ID]命令或使用以下快捷方式:

$ gh me

创建评论、问题和报告

创建评论:

$ gh create-comment donnemartin/gitsome/1 -t "hello world"

创建问题:

$ gh create-issue donnemartin/gitsome -t "title" -b "body"

创建回购:

$ gh create-repo gitsome

选项:在寻呼机中查看

许多gh命令支持-p/--pager在寻呼机中显示结果的选项(如果可用)

用法:

$ gh <command> [param] [options] -p
$ gh <command> [param] [options] --pager

选项:在浏览器中查看

许多gh命令支持-b/--browser在默认浏览器(而不是终端)中显示结果的选项

用法:

$ gh <command> [param] [options] -b
$ gh <command> [param] [options] --browser

请参阅COMMANDS.md有关所有GitHub集成命令、参数、选项和示例的详细列表

记住这些命令有困难吗?看看手边的autocompleter with interactive help来指导您完成每个命令

注意,您可以将gitsome与其他实用程序(如Git-Extras

安装

PIP安装

gitsome托管在PyPI将安装以下命令gitsome

$ pip3 install gitsome

您还可以安装最新的gitsome来自GitHub源,可能包含尚未推送到PyPI的更改:

$ pip3 install git+https://github.com/donnemartin/gitsome.git

如果您没有安装在virtualenv,您可能需要运行sudo

$ sudo pip3 install gitsome

pip3

根据您的设置,您可能还希望运行pip3使用-H flag

$ sudo -H pip3 install gitsome

对于大多数Linux用户来说,pip3可以使用python3-pip套餐

例如,Ubuntu用户可以运行:

$ sudo apt-get install python3-pip

看这个ticket有关更多详细信息,请参阅

虚拟环境安装

您可以将Python包安装在virtualenv要避免依赖项或权限的潜在问题,请执行以下操作

如果您是Windows用户,或者如果您想了解更多有关virtualenv,看看这个guide

安装virtualenvvirtualenvwrapper

$ pip3 install virtualenv
$ pip3 install virtualenvwrapper
$ export WORKON_HOME=~/.virtualenvs
$ source /usr/local/bin/virtualenvwrapper.sh

创建gitsomevirtualenv并安装gitsome

$ mkvirtualenv gitsome
$ pip3 install gitsome

如果pip安装不起作用,您可能默认运行的是Python2。检查您正在运行的Python版本:

$ python --version

如果上面的调用结果是Python 2,请找到Python 3的路径:

$ which python3  # Python 3 path for mkvirtualenv's --python option

如果需要,安装Python 3。调用时设置Python版本mkvirtualenv

$ mkvirtualenv --python [Python 3 path from above] gitsome
$ pip3 install gitsome

如果要激活gitsomevirtualenv稍后再次运行:

$ workon gitsome

要停用gitsomevirtualenv,运行:

$ deactivate

作为Docker容器运行

您可以在Docker容器中运行gitome,以避免安装Python和pip3当地的。要安装Docker,请查看official Docker documentation

一旦安装了docker,您就可以运行gitome:

$ docker run -ti --rm mariolet/gitsome

您可以使用Docker卷让gitome访问您的工作目录、本地的.gitSomeconfig和.gitconfig:

$ docker run -ti --rm -v $(pwd):/src/              \
   -v ${HOME}/.gitsomeconfig:/root/.gitsomeconfig  \
   -v ${HOME}/.gitconfig:/root/.gitconfig          \
   mariolet/gitsome

如果您经常运行此命令,则可能需要定义别名:

$ alias gitsome="docker run -ti --rm -v $(pwd):/src/              \
                  -v ${HOME}/.gitsomeconfig:/root/.gitsomeconfig  \
                  -v ${HOME}/.gitconfig:/root/.gitconfig          \
                  mariolet/gitsome"

要从源构建Docker映像,请执行以下操作:

$ git clone https://github.com/donnemartin/gitsome.git
$ cd gitsome
$ docker build -t gitsome .

启动gitsome

安装后,运行可选的gitsome带有交互式帮助的自动完成程序:

$ gitsome

运行可选的gitsomeShell将为您提供自动完成、交互式帮助、鱼式建议、Python REPL等

正在运行gh命令

运行GitHub集成命令:

$ gh <command> [param] [options]

注意:运行gitsome不需要执行外壳程序gh命令。之后installinggitsome你可以跑gh来自任何shell的命令

运行gh configure命令

要与GitHub正确集成,gitsome必须正确配置:

$ gh configure

针对GitHub企业用户

使用-e/--enterprise标志:

$ gh configure -e

要查看更多详细信息,请访问gh configure部分

启用Bash完成

默认情况下,gitsome查看以下内容locations to enable bash completions

要添加其他bash完成,请更新~/.xonshrc包含bash完成位置的文件

如果~/.xonshrc不存在,请创建它:

$ touch ~/.xonshrc

例如,如果在/usr/local/etc/my_bash_completion.d/completion.bash,将以下行添加到~/.xonshrc

$BASH_COMPLETIONS.append('/usr/local/etc/my_bash_completion.d/completion.bash')

您将需要重新启动gitsome要使更改生效,请执行以下操作

正在启用gh在外部完成制表符gitsome

你可以跑gh外部的命令gitsome外壳完成器。要启用gh此工作流的制表符完成,请将gh_complete.sh本地文件

让bash知道可以完成gh当前会话中的命令:

$ source /path/to/gh_complete.sh

要为所有终端会话启用制表符完成,请将以下内容添加到您的bashrc文件:

source /path/to/gh_complete.sh

重新加载您的bashrc

$ source ~/.bashrc

提示:.是的缩写source,因此您可以改为运行以下命令:

$ . ~/.bashrc

对于Zsh用户

zsh包括与bash完成兼容的模块

下载gh_complete.sh文件,并将以下内容附加到您的.zshrc

autoload bashcompinit
bashcompinit
source /path/to/gh_complete.sh

重新加载您的zshrc

 $ source ~/.zshrc

可选:安装PILPillow

将化身显示为gh megh user命令需要安装可选的PILPillow依赖性

Windows*和Mac:

$ pip3 install Pillow

*请参阅Windows Support有关化身限制的部分

Ubuntu用户,看看这些instructions on askubuntu

支持的Python版本

  • Python 3.4
  • Python 3.5
  • Python 3.6
  • Python 3.7

gitsome由以下人员提供动力xonsh,它当前不支持Python2.x,如本文中所讨论的ticket

支持的平台

  • Mac OS X
    • 在OS X 10.10上测试
  • Linux、Unix
    • 在Ubuntu 14.04 LTS上测试
  • 窗口
    • 在Windows 10上测试

Windows支持

gitsome已在Windows 10上进行了测试,cmdcmder

虽然您可以使用标准的Windows命令提示符,但使用这两种命令提示符都可能会有更好的体验cmderconemu

纯文本化身

命令gh usergh me将永远拥有-t/--text_avatar标志已启用,因为img2txt不支持Windows上的ANSI头像

配置文件

在Windows上,.gitsomeconfig 文件可在以下位置找到%userprofile%例如:

C:\Users\dmartin\.gitsomeconfig

开发人员安装

如果您有兴趣为gitsome,请运行以下命令:

$ git clone https://github.com/donnemartin/gitsome.git
$ cd gitsome
$ pip3 install -e .
$ pip3 install -r requirements-dev.txt
$ gitsome
$ gh <command> [param] [options]

pip3

如果您在安装时收到一个错误,提示您需要Python 3.4+,这可能是因为您的pip命令是为旧版本的Python配置的。要解决此问题,建议安装pip3

$ sudo apt-get install python3-pip

看这个ticket有关更多详细信息,请参阅

持续集成

有关持续集成的详细信息,请访问Travis CI

单元测试和代码覆盖率

在活动的Python环境中运行单元测试:

$ python tests/run_tests.py

使用运行单元测试tox在多个Python环境中:

$ tox

文档

源代码文档将很快在Readthedocs.org请查看source docstrings

运行以下命令构建文档:

$ scripts/update_docs.sh

贡献

欢迎投稿!

回顾Contributing Guidelines有关如何执行以下操作的详细信息,请执行以下操作:

  • 提交问题
  • 提交拉式请求

学分

联系信息

请随时与我联系,讨论任何问题、问题或评论

我的联系信息可以在我的GitHub page

许可证

我在开放源码许可下向您提供此存储库中的代码和资源。因为这是我的个人存储库,您获得的我的代码和资源的许可证来自我,而不是我的雇主(Facebook)

Copyright 2016 Donne Martin

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

HelloGitHub-分享GitHub上有趣、入门级的开源项目

中文|English

分享GitHub上有趣、入门级的开源项目.
兴趣是最好的老师,这里能够帮你找到编程的兴趣!




简介

你好GitHub分享GitHub上有趣、入门级的开源项目。每月28号以月刊的形式更新发布,内容包括:有趣、入门级的开源项目开源书籍实战项目企业级项目等,让你用很短时间感受到开源的魅力,爱上开源!

内容

获得更好的阅读体验官网HelloGitHub 公众号那就是。

📇 🎃 🍺 🍥
第 63 期 第 62 期 第 61 期
第 60 期 第 59 期 第 58 期 第 57 期 第 56 期
第 55 期 第 54 期 第 53 期 第 52 期 第 51 期
第 50 期 第 49 期 第 48 期 第 47 期 第 46 期
第 45 期 第 44 期 第 43 期 第 42 期 第 41 期
第 40 期 第 39 期 第 38 期 第 37 期 第 36 期
第 35 期 第 34 期 第 33 期 第 32 期 第 31 期
第 30 期 第 29 期 第 28 期 第 27 期 第 26 期
第 25 期 第 24 期 第 23 期 第 22 期 第 21 期
第 20 期 第 19 期 第 18 期 第 17 期 第 16 期
第 15 期 第 14 期 第 13 期 第 12 期 第 11 期
第 10 期 第 09 期 第 08 期 第 07 期 第 06 期
第 05 期 第 04 期 第 03 期 第 02 期 第 01 期

欢迎推荐或自荐项目成为HelloGitHub贡献者

赞助



云主机
仅 6 元/月


CDN
开启全网加速

声明


本作品采用署名-非商业性使用-禁止演绎 4.0 国际进行许可.

Loguru — 最强大的 Python 日志记录器

Loguru 一个能彻底解放你的日志记录器。

它即插即用,具备多种方式滚动日志、自动压缩日志文件、定时删除等功能。

除此之外,多线程安全、高亮日志、日志告警等功能也不在话下。

下面就给大家介绍一下这个强大工具的基本使用方法。

Loguru 安装方式很简单,打开终端输入:

pip install loguru

即可完成安装。

1.即开即用

如果你需要输出 debug 日志到终端,可以这么做:

from loguru import logger

logger.debug("That's it, beautiful and simple logging!")

其输出自带高亮:

如果你需要把日志输出到文件,只需要这样:

from loguru import logger
logger.add("file_{time}.log")
logger.debug("That's it, beautiful and simple logging!")

这样就会在当前运行的文件夹下生成 file_当前时间.log 的日志文件:

2.滚动日志与压缩

使用 Loguru 我们可轻易地实现滚动日志。

按时间滚动

比如按时间滚动,我们只需要在 logger.add 参数中添加一个 rotation 参数:

from loguru import logger
logger.add("file_2.log", rotation="12:00")     # 每天12:00会创建一个新的文件
logger.debug("That's it, beautiful and simple logging!")

这样,如果当前时间过了这个设定的时间,它就会生成一个新的日志文件。如果没有则使用原来的日志文件:

如图所示,过了设定的时间,则将原来的 file_2.log 重命名,并添加一个新的 file_2.log 文件。

按大小滚动

除了按时间滚动日志外,Loguru 还可以按日志大小滚动:

from loguru import logger
logger.add("file_1.log", rotation="1 MB")    # 滚动大日志文件
logger.debug("That's it, beautiful and simple logging!")

这样,一旦日志文件大小超过 1 MB 就会产生新的日志文件。

压缩日志

如果你不想删除原有日志文件,Loguru 还支持将日志直接压缩:

from loguru import logger
logger.add("file_Y.log", compression="zip")    # 压缩日志

3.其他特性

自定义颜色

Loguru 是支持自定义颜色的,如果你不喜欢它默认的颜色,可以这么改:

logger.add(sys.stdout, colorize=True, format="<green>{time}</green> <level>{message}</level>")

类似于HTML标签 <green></green> 标签中间的文字将会被标记为绿色。

多进程安全

Loguru 默认情况下是线程安全的,但它不是多进程安全的。不过如果你需要多进程/异步记录日志,它也能支持,只需要添加一个 enqueue 参数:

logger.add("somefile.log", enqueue=True)

支持Backtrace

对于日志而言,没有错误堆栈的日志是没有灵魂的。Loguru 允许显示整个堆栈信息来帮助你发现问题(包括变量)。

比如下面这个例子:

logger.add("out.log", backtrace=True, diagnose=True)  # Caution, may leak sensitive data in prod

def func(a, b):
    return a / b

def nested(c):
    try:
        func(5, c)
    except ZeroDivisionError:
        logger.exception("What?!")

nested(0)

日志将会是这样的:

非常清晰明了。

邮件告警

Loguru 可以和强大的邮件通知模块 notifiers 库结合使用,以在程序意外失败时接收电子邮件,或发送许多其他类型的通知。

import notifiers

params = {
    "username": "you@gmail.com",
    "password": "abc123",
    "to": "dest@gmail.com"
}

# 初始化时发送一封邮件
notifier = notifiers.get_notifier("gmail")
notifier.notify(message="The application is running!", **params)

# 发生Error日志时,发邮件进行警报
from notifiers.logging import NotificationHandler

handler = NotificationHandler("gmail", defaults=params)
logger.add(handler, level="ERROR")

这样配置之后,每次产生 Error 日志,程序都会自动向你的邮箱发送告警,真的极其方便。

除了这些特性外,Loguru 还支持与 Python 原生的 Logging 模块兼容使用,你可以将原始的标准日志记录器记录的所有信息转移到Loguru中。

你还可以基于 Loguru 定制新的日志 Level,定制自己喜欢的结构化数据,详情可见 Loguru 的官方文档:

https://github.com/Delgan/loguru

我们的文章到此就结束啦,如果你喜欢今天的 Python 教程,请持续关注Python实用宝典。

有任何问题,可以在公众号后台回复:加群,回答相应验证信息,进入互助群询问。

原创不易,希望你能在下面点个赞和在看支持我继续创作,谢谢!

给作者打赏,选择打赏金额
¥1¥5¥10¥20¥50¥100¥200 自定义

​Python实用宝典 ( pythondict.com )
不只是一个宝典
欢迎关注公众号:Python实用宝典

超简单一键美化你的文章—使其更具可读性

在平时写文章的时候,我都会注意在中文和英文单词之间保留一个空格的习惯,这样能使文本具有良好的可读性。

但是我经常忽略某些半角字符(数字和符号)与中文之间的空格,导致可读性比较差,在阅读别人的文章或者修改别人的文章时候,也经常为烦恼他人没有这种优化可读性的细节。

现在,有一个很棒的工具,叫做 pangu , 它可以在中文、日文、韩文和半角字符(字母,数字和符号)之间自动插入空格。

有了它,你可以在每次写完文章后利用 pangu 一键美化文章。也可以用 pangu 美化别人的文章:

import pangu

new_text = pangu.spacing_text('你可以在每次写完文章后利用pangu一键美化文章。也可以用pangu 美化别人的文章:')
print(new_text)
# new_text = '你可以在每次写完文章后利用 pangu 一键美化文章。也可以用 pangu 美化别人的文章:'

如上所示,非常方便。当然你也可以自己用正则表达式去匹配并美化,但是用起来肯定没有 pangu 方便。

下面教大家 pangu 模块的使用方法:

1.准备

开始之前,你要确保Python和pip已经成功安装在电脑上,如果没有,请访问这篇文章:超详细Python安装指南 进行安装。

(可选1) 如果你用Python的目的是数据分析,可以直接安装Anaconda:Python数据分析与挖掘好帮手—Anaconda,它内置了Python和pip.

(可选2) 此外,推荐大家用VSCode编辑器来编写小型Python项目:Python 编程的最好搭档—VSCode 详细指南

Windows环境下打开Cmd(开始—运行—CMD),苹果系统环境下请打开Terminal(command+空格输入Terminal),输入命令安装依赖:

pip install -U pangu

2.使用

安装完成之后,你可以尝试写一些简单的句子并美化它们:

import pangu

new_text = pangu.spacing_text('Windows环境下打开Cmd(开始—运行—CMD),苹果系统环境下请打开Terminal(command+空格输入Terminal)')
print(new_text)
# new_text = 'Windows 环境下打开 Cmd (开始 — 运行 —CMD),苹果系统环境下请打开 Terminal (command + 空格输入 Terminal)'

一键执行

你也可以不写 python 文件,直接通过 -m 参数执行命令:

python -m pangu "為什麼小明有問題都不Google?因為他有Bing"
# 為什麼小明有問題都不 Google?因為他有 Bing

此外,pangu 也支持 pangu 命令直接格式化文本:

pangu "請使用uname -m指令來檢查你的Linux作業系統是32位元或是[敏感词已被屏蔽]位元"
# 請使用 uname -m 指令來檢查你的 Linux 作業系統是 32 位元或是 [敏感词已被屏蔽] 位元

文件支持

通过 -f 参数,pangu 支持把指定的文件内容进行美化,然后输出到另一个文件中:

echo "未來的某一天,Gmail配備的AI可能會得出一個結論:想要消滅垃圾郵件最好的辦法就是消滅人類" >> path/to/file.txt
pangu -f path/to/file.txt >> pangu_file.txt
cat pangu_file.txt
# 未來的某一天,Gmail 配備的 AI 可能會得出一個結論:想要消滅垃圾郵件最好的辦法就是消滅人類

管道支持 (UNIX)

在 UNIX 系统中,比如 Linux 和 MacOS,pangu还支持使用管道 ( | ) 命令美化文本:

echo "心裡想的是Microservice,手裡做的是Distributed Monolith" | pangu
# 心裡想的是 Microservice,手裡做的是 Distributed Monolith

echo "你從什麼時候開始產生了我沒使用Monkey Patch的錯覺?" | python -m pangu
# 你從什麼時候開始產生了我沒使用 Monkey Patch 的錯覺?

两句命令的效果一样,如果你无法直接使用 pangu 命令,可以尝试 python -m pangu,他们能达到一样的效果。

我们的文章到此就结束啦,如果你喜欢今天的 Python 教程,请持续关注Python实用宝典。

有任何问题,可以在公众号后台回复:加群,回答相应验证信息,进入互助群询问。

原创不易,希望你能在下面点个赞和在看支持我继续创作,谢谢!

给作者打赏,选择打赏金额
¥1¥5¥10¥20¥50¥100¥200 自定义

​Python实用宝典 ( pythondict.com )
不只是一个宝典
欢迎关注公众号:Python实用宝典

漂亮的GitHub个人总览 ,原来这么容易实现

前段时间,GitHub悄悄地发布了一个新功能:Profile README.

翻译成中文即简历型README,好听一点就是个人自述型简历,简单点就是个人GitHub总览

下面给大家讲讲怎么通过 GitHub API 创建一个能够自更新的总览。

1.首先,创建一个GitHub仓库:

创建一个与你的GitHub帐户同名的存储库(在我的情况下为github.com/Ckend/Ckend

向其添加一个README.md,我写入了以下内容:

“To be continued…”

如图所示:

然后GitHub将在你的个人资料页面顶部呈现该README内容,对我来说就是github.com/Ckend

如图所示,你用户名的这个仓库的 README.md 将成为你的个人资料首页的展示内容。

2.美化你的展示内容

首先,我们可以加一个GitHub的基本统计信息

这是官方给出的统计组件API,使用起来很方便,你只需要往你的README.md里添加下述代码即可:

<img align="left" src="https://github-readme-stats.vercel.app/api?username=你的账号用户名&include_all_commits=true&count_private-true&custom_title=你的账号用户名'%20GitHub%20Stats&line_height=30&show_icons=true&hide_border=true&bg_color=192133&title_color=efb752&icon_color=efb752&text_color=70bed9">

此外GitHub官方还提供了一个展示自己最常用语言的接口。

你可以在README.md里添加下述内容展示这个图表:

<img align="right" src="https://github-readme-stats.vercel.app/api/top-langs/?username=ckend">

你还可以带一个 &layout=compact 参数展示横版图表:

<img align="right" src="https://github-readme-stats.vercel.app/api/top-langs/?username=ckend&layout=compact">

另外,​我们还可以加上技术栈图标:

利用 https://img.shields.io 提供的图标,可以轻松实现这点,在README键入以下内容即可:

### 技术栈

![Python](https://img.shields.io/badge/-Python-192133?style=flat-square&logo=python&logoColor=white)
![Django](https://img.shields.io/badge/-Django-192133?style=flat-square&logo=figma&logoColor=white)
![PHP](https://img.shields.io/badge/-PHP-192133?style=flat-square&logo=figma&logoColor=white)
![MySQL](https://img.shields.io/badge/-MySQL-192133?style=flat-square&logo=mysql&logoColor=white)
![Redis](https://img.shields.io/badge/-Redis-192133?style=flat-square&logo=redis&logoColor=white)
![Elasticsearch](https://img.shields.io/badge/-Elasticsearch-192133?style=flat-square&logo=elasticsearch&logoColor=white)
![Kafka](https://img.shields.io/badge/-Kafka-192133?style=flat-square&logo=apache-kafka&logoColor=white)

当然,你要根据自己的情况做修改。

此外,shields网站还能自定义图标,可以用于展示自己的项目:

### 项目
[![pythondict-quant](https://img.shields.io/badge/pythondict-quant-192133?style=flat-square)](https://github.com/Ckend/pythondict-quant)
[![scihub-cn](https://img.shields.io/badge/scihub-cn-192133?style=flat-square)](https://github.com/Ckend/scihub-cn)

你可以按照自己的情况选择以上任意一种组件来美化总览。

完成一个漂亮的总览,能让你更有动力去维护GitHub仓库,所以一定要动手试试。

下面给大家提供一份我的总览完整版:

<img align="left" src="https://github-readme-stats.vercel.app/api?username=Ckend&include_all_commits=true&count_private-true&custom_title=Ckend'%20GitHub%20Stats&line_height=30&show_icons=true&hide_border=true&bg_color=192133&title_color=efb752&icon_color=efb752&text_color=70bed9">

### 技术栈
​
![Python](https://img.shields.io/badge/-Python-192133?style=flat-square&logo=python&logoColor=white)
![Django](https://img.shields.io/badge/-Django-192133?style=flat-square&logo=figma&logoColor=white)
![PHP](https://img.shields.io/badge/-PHP-192133?style=flat-square&logo=figma&logoColor=white)
![MySQL](https://img.shields.io/badge/-MySQL-192133?style=flat-square&logo=mysql&logoColor=white)
![Redis](https://img.shields.io/badge/-Redis-192133?style=flat-square&logo=redis&logoColor=white)
![Elasticsearch](https://img.shields.io/badge/-Elasticsearch-192133?style=flat-square&logo=elasticsearch&logoColor=white)
![Kafka](https://img.shields.io/badge/-Kafka-192133?style=flat-square&logo=apache-kafka&logoColor=white)

### 项目
[![pythondict-quant](https://img.shields.io/badge/pythondict-quant-192133?style=flat-square)](https://github.com/Ckend/pythondict-quant)
[![scihub-cn](https://img.shields.io/badge/scihub-cn-192133?style=flat-square)](https://github.com/Ckend/scihub-cn)

大家可以参考这个方案进行修改,绘制一个属于自己的漂亮总览。

我们的文章到此就结束啦,如果你喜欢今天的 Python 教程,请持续关注Python实用宝典。

有任何问题,可以在公众号后台回复:加群,回答相应验证信息,进入互助群询问。

原创不易,希望你能在下面点个赞和在看支持我继续创作,谢谢!

给作者打赏,选择打赏金额
¥1¥5¥10¥20¥50¥100¥200 自定义

​Python实用宝典 ( pythondict.com )
不只是一个宝典
欢迎关注公众号:Python实用宝典