我希望保持一个可靠的日志系统运行,但也有必要引发异常。这段代码实现了我想要的目标,但它看起来很笨拙,而且不太 Pythonic。什么是更好的选择?
import logging
if not condition_met:
missing = set_one - set_two
logging.error('Missing keys: {}'.format(missing))
raise ValueError('Missing keys: {}'.format(missing))
Run Code Online (Sandbox Code Playgroud) 我编写了一个最小的 C 函数(带有附带的头文件),目的是创建一个 Cython 包装器,该包装器可以从其他地方的 Python 文件中使用 C 代码。
我的文件是这样的:
C文件:
/* engine.c */
#include <stdio.h>
#include "customlib.h"
int engine(int value, int iterations) {
/* declare iteration index */
int idx;
for (idx = 0; idx < iterations; idx = idx + 1) {
value = value * 3;
}
/* return value that should be accessible by the Python module */
return value;
}
Run Code Online (Sandbox Code Playgroud)
C头文件:
/* customlib.h */
#ifndef CUSTOM_HEADER_H
#define CUSTOM_HEADER_H
/* engine function */
int engine(int value, …Run Code Online (Sandbox Code Playgroud) 如果我有一个numpy.ndarray,比如300个点(现在是1 x 300),我想每30分选择10个点,我该怎么做?
换句话说:我想要前10个点,然后跳过20个,然后再抓10个,然后跳过10个......直到数组结束.
我有一些计算功能,用于驱动硬件设置的软件配置.在某些情况下,用户可能输入无效的配置值.我通过在使用无效值时抛出异常来处理此问题,或者只是在配置有效时返回我的计算值:
def calc_exhale_dur(breath_rate, inh_dur, breath_hold_dur):
"""Calculate exhalation duration.
Args:
breath_rate (float): animal breath rate (br/min)
inh_dur (float): animal inhalation duration (ms)
breath_hold_duration (float): animal breath hold duration (ms)
"""
single_breath_dur = calc_breath_dur(breath_rate)
exhale_dur = single_breath_dur - (inh_dur + breath_hold_dur)
if (inh_dur + breath_hold_dur + exhale_dur) > single_breath_dur:
raise error.ConfigurationError
elif exhale_dur <= 0:
raise error.ConfigurationError
else:
return exhale_dur
Run Code Online (Sandbox Code Playgroud)
以这种方式这样做被认为是不好的做法吗?如果有一个返回值,我是否总是需要一些有效的返回值?我正在努力学习如何最好地编写Pythonic代码,同时仍然满足我的计算方法的需要.
我正在开发一个包,其他人将使用它来编写处理脚本.对于测试/调试/非疯狂的目的,我想在我的代码中包含一些日志记录语句,特别是使用logging_setup()我为另一个项目开发的实用程序函数来进行格式化/文件输出控制.
因为我不是在编写一个自包含的应用程序,而是一个意图被其他程序调用的库,我很困惑我应该使用我的logging_setup()实用程序来生成我想要的所需的日志记录结果.这让我想知道在我的软件包中使用日志系统是否是一个好主意.
我应该在哪里使用我的logging_setup()实用程序?
编辑:这是我上面提到的功能:
def logging_setup(cfg_path=definitions.LOG_CONFIG_PATH, lvl=logging.INFO):
"""Setup logging tool from YAML configuration file.
This should only be run once. Formatted (or configured) logging can only be
done from within functions/classes in other modules.
"""
# create directory for log files if not already there
try:
os.makedirs(definitions.LOGS_PATH)
except OSError as e:
if e.errno != errno.EEXIST:
raise
# configure logging from yaml config file
if os.path.exists(cfg_path):
with open(cfg_path, 'rt') as f:
config = yaml.safe_load(f.read())
logging.config.dictConfig(config) …Run Code Online (Sandbox Code Playgroud)