小编JS.*_*JS.的帖子

Argparse:在'--help'中包含默认值的方法?

假设我有以下argparse片段:

diags.cmdln_parser.add_argument( '--scan-time',
                     action  = 'store',
                     nargs   = '?',
                     type    = int,
                     default = 5,
                     help    = "Wait SCAN-TIME seconds between status checks.")
Run Code Online (Sandbox Code Playgroud)

目前,--help退货:

usage: connection_check.py [-h]
                             [--version] [--scan-time [SCAN_TIME]]

          Test the reliability/uptime of a connection.



optional arguments:
-h, --help            show this help message and exit
--version             show program's version number and exit
--scan-time [SCAN_TIME]
                    Wait SCAN-TIME seconds between status checks.
Run Code Online (Sandbox Code Playgroud)

我更喜欢这样的东西:

--scan-time [SCAN_TIME]
                    Wait SCAN-TIME seconds between status checks.
                    (Default = 5)
Run Code Online (Sandbox Code Playgroud)

偷看帮助格式化程序代码显示有限的选项.是否有一种聪明的方式来argparse--scan-time类似的方式打印默认值,或者我应该只是 …

python argparse

265
推荐指数
4
解决办法
4万
查看次数

Python相当于PHP的内爆?

Python中的PHP内爆是否相当?我已经阅读并拆分了一组分隔的单词,现在我想以随机顺序对它们进行排序,然后用两个空格打印出来.

implode - 使用字符串连接数组元素

http://php.net/manual/en/function.implode.php

php python implode

88
推荐指数
2
解决办法
6万
查看次数

Python异常的最佳实践?

创建例外的最佳做法是什么?我刚看到这个,我不知道我是否应该感到恐惧或喜欢它.我在书中多次阅读异常永远不会持有字符串,因为字符串本身可以抛出异常.这有什么真相吗?

基本上我从脚本的理解是这样做,所以所有内部Python库将有一个共同的错误消息格式(迫切需要的东西)所以我可以理解为什么把错误消息字符串是一个好主意.(几乎每种方法都会抛出异常,因为完全不需要无效的通过).

有问题的代码如下:

"""
Base Exception, Error
"""
class Error(Exception):
    def __init__(self, message):
        self.message = message

    def __str__(self):
        return "[ERROR] %s\n" % str(self.message)

    def log(self):
        ret = "%s" % str(self.message)
        if(hasattr(self, "reason")):
            return "".join([ret, "\n==> %s" % str(self.reason)])
        return ret

class PCSException(Error):
    def __init__(self, message, reason = None):
        self.message = message
        self.reason = reason
    def __str__(self):
        ret = "[PCS_ERROR] %s\n" % str(self.message)
        if(self.reason != None):
            ret += "[REASON] %s\n" % str(self.reason)
        return ret
Run Code Online (Sandbox Code Playgroud)

这只是冰山一角,但有人可以给我一些洞察力,这是一个什么使这个可怕的想法?或者,如果有一个更好的异常编码过程/风格.

python exception

60
推荐指数
4
解决办法
4万
查看次数

Pytest:取消选择测试

使用pytest,可以使用装饰器标记测试

@pytest.mark.slow
def some_slow_test():
    pass
Run Code Online (Sandbox Code Playgroud)

然后,从命令行,可以告诉pytest跳过标记为"慢"的测试

pytest -k-slow
Run Code Online (Sandbox Code Playgroud)

如果我有一个额外的标签:

@pytest.mark.long
def some_long_test()
    pass
Run Code Online (Sandbox Code Playgroud)

我希望能够跳过长期和慢速测试.我试过这个:

pytest -k-slow -k-long
Run Code Online (Sandbox Code Playgroud)

还有这个:

pytest -k-slow,long
Run Code Online (Sandbox Code Playgroud)

似乎都不起作用.

在命令行中,如何告诉pytest跳过慢和长测试?

python pytest

43
推荐指数
3
解决办法
1万
查看次数

IPython*脚本*的命令行选项?

我经常被要求调试其他人编写的Python脚本.我想将这些脚本发送到IPython,因此它会在脚本失败时插入到IPython shell中.

不幸的是,我找不到发送脚本所需的命令行选项的方法.

当我将脚本及其选项传递为以下内容时,IPython假定所有内容都适用于IPython:

ipython <script_name> <script_options>
Run Code Online (Sandbox Code Playgroud)

有解决方案或解决方法吗?

python ipython

36
推荐指数
3
解决办法
2万
查看次数

有没有办法在不加载Windows的Python的情况下查看cPickle或Pickle文件内容?

我使用cPickle来保存每次运行程序的数据集.由于我有时需要在不运行代码的情况下查看数据的轮廓,因此我想通过双击文件来快速查看内容.我试图避免每次都加载一个终端并将python指向一个文件,只是为了运行一些print脚本.

我找了Notepad ++插件但找不到任何东西.

有一些简单的方法来做到这一点?有没有人有什么建议?

注意:我运行Windows 7.

python pickle

26
推荐指数
3
解决办法
3万
查看次数

禁用每个方法/功能的记录?

我是Python日志的新手,我可以很容易地看到它对我提出的家庭酿造解决方案的优越性.

我似乎无法找到答案的一个问题:如何基于每个方法/函数压制记录消息?

我的假设模块包含一个函数.在我开发时,日志调用是一个很好的帮助:

logging.basicConfig(level=logging.DEBUG,
                format=('%(levelname)s: %(funcName)s(): %(message)s'))
log = logging.getLogger()

my_func1():
    stuff...
    log.debug("Here's an interesting value: %r" % some_value)
    log.info("Going great here!")
    more stuff...
Run Code Online (Sandbox Code Playgroud)

当我在'my_func1'上完成工作并开始处理第二个函数'my_func2'时,来自'my_func1'的日志消息开始从"有用"变为"杂乱".

是否存在单行魔术语句,例如'logging.disabled_in_this_func()',我可以将其添加到'my_func1'的顶部以禁用'my_func1'中的所有日志记录调用,但仍然在所有其他函数/方法中保留日志记录调用不变?

谢谢

linux,Python 2.7.1

python logging

14
推荐指数
2
解决办法
4411
查看次数

我可以更改Python绑定方法对象的__str __()属性吗?

我想改变__str__()我的一个类的方法的属性.

(注意:不要与"试图改变方法__str__()" 混淆.)

我有一个类MyClass,它有一个方法'some_method'.我可以改变MyClass显示方式:

class MyClass():
    def __init__(self): pass
    def some_method(self): pass
    def __str__(self): return "I'm an instance of MyClass!"
Run Code Online (Sandbox Code Playgroud)

当我实例化并打印MyClass时:

print(my_class)
Run Code Online (Sandbox Code Playgroud)

我明白了:

I'm an instance of MyClass!

当我

print(my_class.some_method)
Run Code Online (Sandbox Code Playgroud)

我明白了:

<bound method my_class.some_method of <gumble margle object at mumble-jumble>>

我想改为:

some_method in the instance my_class you Dope!

我已经尝试重写str方法some_method:

def some_method(self):
    def __str__(self):
        return "You dope!"
Run Code Online (Sandbox Code Playgroud)

但没有爱.

试图在IPython中暴力破解它并没有改善:

my_class.some_method.__str__ = lambda: "You Dope!"
Run Code Online (Sandbox Code Playgroud)

AttributeError: 'method' object attribute '__str__' is …

python overriding instance python-3.x

12
推荐指数
1
解决办法
2070
查看次数

根据Python3中的消息日志记录级别修改日志消息格式

在这里问了python 2的这个问题,但是当Python 3.2.3的答案不再有效时再次遇到了问题.

这里的代码适用于Python 2.7.3:

import logging

# Attempt to set up a Python3 logger than will print custom messages
# based on each message's logging level.
# The technique recommended for Python2 does not appear to work for
# Python3

class CustomConsoleFormatter(logging.Formatter):
    """
    Modify the way DEBUG messages are displayed.

    """
    def __init__(self, fmt="%(levelno)d: %(msg)s"):
        logging.Formatter.__init__(self, fmt=fmt)

    def format(self, record):

        # Remember the original format
        format_orig = self._fmt

        if record.levelno == logging.DEBUG:
            self._fmt = "DEBUG: %(msg)s"

        # …
Run Code Online (Sandbox Code Playgroud)

logging python-3.x

11
推荐指数
2
解决办法
4662
查看次数

配置子记录器

每次我认为我理解了日志记录模块时,gremlins会进来并改变它的工作方式.(好吧,我承认,gremlin可能是我改变我的代码.)

我在这做错了什么?

> ipython
> import logging
> log = logging.Logger("base")
> log.addHandler(logging.StreamHandler())

> log.critical("Hi")
Hi

> log2 = log.getChild("ment")

> log2.critical("hi")
No handlers could be found for logger "base.ment"
Run Code Online (Sandbox Code Playgroud)

我本可以发誓过去,我能够使用儿童记录器而无需额外配置......

python logging

8
推荐指数
1
解决办法
4243
查看次数