小编Tho*_*ger的帖子

Python3添加日志记录级别

我有这个代码对我来说很好.

import logging
import logging.handlers

logger = None


def create_logger():
    global logger
    logger = logging.getLogger('Logger')
    logger.setLevel(logging.DEBUG)
    handler = logging.handlers.RotatingFileHandler("C:/Users/user/Desktop/info.log", maxBytes=1000000, backupCount=20)
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    handler.setFormatter(formatter)
    logger.addHandler(handler)


create_logger()
logger.info("Text info")
logger.debug("Text debug")
logger.warning("Text warning")
logger.error("Text error")
logger.critical("Text critical")
Run Code Online (Sandbox Code Playgroud)

输出看起来很棒:

2017-12-19 15:06:43,021 - 记录器 - 信息 - 文本信息
2017-12-19 15:06:43,021 - 记录器 - 调试 - 文本调试
2017-12-19 15:06:43,022 - 记录器 - 警告 - 正文警告
2017-12-19 15:06:43,022 - 记录器 - 错误 - 文本错误
2017-12-19 15:06:43,022 - 记录器 …

python logging python-3.5

7
推荐指数
1
解决办法
3031
查看次数

如何在不调试时禁用PyCharm中的PyDev控制台调试器?

每当我在PyCharm中运行脚本时,它就会启动PyDev调试器(使用IPython终端).

  • 我的脚本不会失败或引发任何错误,并且
  • 我没有调试:我正在运行菜单中的"运行" - > "运行file.py".

我已经弄清楚如何禁用IPython终端,但它只是运行"普通"终端.我只想运行脚本并将输出打印到控制台,然后退出.

如何禁用此功能?

pycharm

6
推荐指数
1
解决办法
2273
查看次数

如何永久取消设置 ArangoDB 文档的属性?

我想从 ArangoDB 的文档中删除一个属性。

我认为正确的方法是使用函数UNSET(doc, attributeName1, ..., attributeNameN)。然而,仅凭这一点,数据库中没有任何变化。

例子:

let target_key = "42"

FOR doc IN myCollection
    FILTER doc._key == target_key
    RETURN UNSET(doc, "myAttribute")
Run Code Online (Sandbox Code Playgroud)

该示例返回没有属性的原始文档myAttribute,但新版本未保存到数据库中,因此这似乎只是一个投影副本。

arangodb

5
推荐指数
2
解决办法
1190
查看次数

带有用于 ArangoDB 的 python-arango 驱动程序的 UPSERT

我使用python-arango作为 ArangoDB 的驱动程序,似乎没有UPSERT接口。

我打算用 python-arango标记它但我没有足够的代表来创建新标签

我正在使用如下所示的功能进行管理,但我想知道是否有更好的方法来做到这一点?

def upsert_document(collection, document, get_existing=False):
    """Upserts given document to a collection. Assumes the _key field is already set in the document dictionary."""
    try:
        # Add insert_time to document
        document.update(insert_time=datetime.now().timestamp())
        id_rev_key = collection.insert(document)
        return document if get_existing else id_rev_key
    except db_exception.DocumentInsertError as e:
        if e.error_code == 1210:
            # Key already exists in collection
            id_rev_key = collection.update(document)
            return collection.get(document.get('_key')) if get_existing else id_rev_key
    logging.error('Could not save document {}/{}'.format(collection.name, document.get('_key'))) …
Run Code Online (Sandbox Code Playgroud)

python-3.x arangodb python-arango

5
推荐指数
1
解决办法
809
查看次数

为什么最简单的 requests_mock 示例在使用 pytest 时失败?

我有一个特殊的问题requests_mock。我想用它pytest来测试我的 API 包装器库。

我尝试使用requests_mock docs 中第一个示例,除了我将它放在test_mock() -function 中并添加了一个assert-statement 供 pytest 发现它。

以下代码失败:

# tests/test_mock.py

import requests
import requests_mock

with requests_mock.Mocker() as m:
    def test_mock():
        m.get('http://test.com', text='resp')
        assert requests.get('http://test.com').text == 'resp'
Run Code Online (Sandbox Code Playgroud)

但是,在 ipython 中运行以下示例时,它按预期工作。这是示例中的确切代码:

with requests_mock.Mocker() as m:
    m.get('http://test.com', text='resp')
    print(requests.get('http://test.com').text)

# prints 'resp'
Run Code Online (Sandbox Code Playgroud)

因为我可以requests_mock从 ipython 工作,所以我认为问题出在 pytest 上,但我可能是错的。

似乎根本没有使用适配器,因此请求会向目标 url 发送一个真正的 http 请求,而不是使用模拟对象。


我正在使用 Python 3.6.3 (Anaconda3)、requests_mock 1.3.0 和 pytest 3.3.0

运行失败的代码的输出:

C:\dev\mylib>pytest -v …
Run Code Online (Sandbox Code Playgroud)

python mocking pytest python-requests

5
推荐指数
1
解决办法
4092
查看次数

Read data from TFRecord file used in Object Detection API

I want to read the data stored in a TFRecord file that I've used as a train record in TF Object Detection API.

However, I get an InvalidArgumentError: Input to reshape is a tensor with 91090 values, but the requested shape has 921600. I don't understand what the root of the error is, even though the discrepancy seems to be a factor of 10.

Question: How can I read the file without this error?

  • I can't rule out …

python tensorflow tfrecord object-detection-api

5
推荐指数
1
解决办法
3294
查看次数

如何将 JavaScript 类实例与对象合并?

我想将对象的属性/值与类实例合并。(我不确定 JS 中正确的术语是什么,但示例应该能澄清)

我的尝试是使用扩展语法。见下文。

我有一个文件实例:

const files = listOfFilesFromDragNdrop();
let file = files[0];

console.log(file)
Run Code Online (Sandbox Code Playgroud)

输出类似:

File(2398)
lastModified: 1530519711960
lastModifiedDate: Mon Jul 02 2018 10:21:51 GMT+0200
name: "my_file.txt"
preview: "blob:http://localhost:8080/6157f5d5-925a-4e5d-a466-24576ba1bf7c"
size: 2398
type: "text/plain"
webkitRelativePath: ""
Run Code Online (Sandbox Code Playgroud)

添加后,我使用FileReader .readAsText() 获取内容,并将其包装在一个对象中,例如:

contentObject = getFileContentFromFile()
console.log(contentObject)
Run Code Online (Sandbox Code Playgroud)

会输出类似:

{ 
    preview: "blob:http://localhost:8080/6157f5d5-925a-4e5d-a466-24576ba1bf7c",
    content: "Lorem ipsum some text here." 
}
Run Code Online (Sandbox Code Playgroud)

我想最终得到一个合并的对象,例如:

{ 
    // "preview" is the key used to map files and content
    preview: "blob:http://localhost:8080/6157f5d5-925a-4e5d-a466-24576ba1bf7c",

    // "text" is the new field with the content …
Run Code Online (Sandbox Code Playgroud)

javascript spread-syntax

5
推荐指数
2
解决办法
4322
查看次数

为什么Twine 1.9.1仍上传到旧版PyPi?

我想按照“ 迁移到PyPI.org”文档中的说明将包上传到pypi.org ,但是Twine则上传到https://upload.pypi.org/legacy/

pypi.python.org/pypi/mypolr上可用,但在pypi.org找不到

我尝试阅读其他一些问题,教程和指南。

我的pip.ini文件(我在Windows 10上)如下所示:

[distutils]
index-servers =
    pypi

[pypi]
Run Code Online (Sandbox Code Playgroud)

我没有存储用户名或密码,因此[pypi]部分为空(如迁移文档中所述)。

我已将.ini文件放入用户文件夹,并确认(根据此答案)它实际上正在使用我设置的文件(使用环境变量PIP_CONFIG_FILE)。

害怕我出了点问题,因此我也尝试了没有pip.ini文件的情况,以使Twine使用其默认值。

我正在使用Python 3.6.3(来自Anaconda),并且我的工具版本为:

  • 麻线1.9.1(迁移文档称应为1.8+)
  • setuptools 38.2.3(迁移文档说应该为27+)

不管它是否相关,这里有一些更多信息:

  • 链接到我的setup.py
  • setupsetuptools从而不是从distutils.core
  • README.rst用作long description,但在PyPi页中仅显示标题的前8个星号。(比较
  • 我上传的软件包的版本是0.2.1(在发布时)
  • setuptools_scm 用于从git标签获取版本
  • 构建是用 python setup.py sdist bdist_wheel

请让我知道是否还有其他信息可以帮助您解决这一问题。

python pypi twine

4
推荐指数
2
解决办法
359
查看次数

Matplotlib:颜色栏中的中心颜色,具有使用索引颜色值的发散颜色图

这部分是两个问题:

  • 如何将(发散的)颜色图围绕某个给定值居中?
  • 如何做到这一点,同时将数据中的索引映射到颜色图中的值?(下面进一步解释)

某些类型的数据(例如 BMI 分数)具有自然的中点。在 matplotlib 中,有几个不同的颜色图。我希望颜色图的中心,即光谱的“中间”位于“理想”BMI 分数上,与绘制的 BMI 分数分布无关。

BMI 类别阈值是:bmi_threshold = [16, 17, 18.5, 25, 30, 35].

在下面的代码中,我绘制了 300 个随机 BMI 值的散点图,其中 x 轴为体重,y 轴为身高,如下图所示。

在第一张图片中,我使用了- 调用的 - 参数np.digitize(bmi, bmi_threshold),但随后颜色条中的每个值也变成了,而我希望颜色条刻度位于 BMI 分数中(大约 15-40)。(是对应于和的 300 个随机 BMI 分数的数组)cax.scatter()range(7)bmixy

BMI 阈值分布不均匀,因此如果我仅更改颜色条中的刻度标签,则将无法正确表示与数字化类别索引(例如2和之间)的距离。3

在与如下所示的代码一起使用的第二张图像中,似乎没有正确居中于“理想”BMI 分数 22。我尝试使用“使散点颜色条仅显示vmin/vmax ”来调整颜色栏中的颜色范围,但它似乎没有按(我)预期的方式工作。

low此外,我认为我可以通过设置和high到[0, 1] 之外的值(例如 [-0.5,1.5] )来“挤压”颜色来强调“中心”又名“理想”分数cmap(np.linspace(low, high, 7)),但随后我遇到了更多麻烦使颜色条居中。

我做错了什么,我该如何实现这一目标?

import numpy as np
import …
Run Code Online (Sandbox Code Playgroud)

python matplotlib

4
推荐指数
1
解决办法
4382
查看次数

按像素值移动 matplotlib xticklabels

如何将刻度标签移动几个像素?

就我而言,我想将X 轴上的This is class #N -labels 向右移动几个像素。

知道的 horizontalalign/harightcenterleft; 但我想“改善”right对齐的外观。

以下面的例子为例,它将产生如下图所示的图:

import pandas as pd
import numpy as np

categories = ['This is class #{}'.format(n) for n in range(10)]
data = {
    'Value': [categories[np.random.randint(10)] for _ in range(100)], 
    'id': [1000+i for i in range(100)]
}

df = pd.DataFrame(data)

ax = df.Value.value_counts().sort_index().plot(kind='bar', rot=45)
plt.xticks(ha='right')
Run Code Online (Sandbox Code Playgroud)

结果是:

我主观上认为,如果将标签向右平移以便将勾号放在“#”上,情节会更好看。换句话说,是rightcenter对齐选项之间的“中间地带” 。

旁注

我正在使用熊猫,但我相信这与问题无关,因为它无论如何都使用 matplotlib 进行绘图。

该 …

python matplotlib python-3.x

0
推荐指数
1
解决办法
972
查看次数