簡體   English   中英

命令行程序的消息傳遞

[英]messaging for command line programs

我傾向於編寫許多命令行實用程序,並且想知道是否存在使用Python傳遞用戶消息的標准方法。 具體來說,我想以與Unix約定一致的方式打印錯誤和警告消息以及其他更多的對話輸出。 我可以使用內置的打印功能自己生成這些消息,但是消息具有統一的結構,因此,似乎有一個軟件包可以為我自己處理這些消息。

例如,對於直接在命令行中運行的命令,您可能會收到以下消息:

This is normal output.
error: no files given.
error: parse.c: no such file or directory.
error: parse.c:7:16: syntax error.
warning: /usr/lib64/python2.7/site-packages/simplejson:
    not found, skipping.

如果這些命令可能在腳本或管道中運行,則應包括其名稱:

grep: /usr/dict/words: no such file or directory.

如果能夠處理詳細程度,那將是很好的。

這些事情在概念上都是相對簡單的,但是會給每個打印語句帶來很多額外的條件和復雜性。

我已經看過Python中的日志記錄工具,但是它看起來過於復雜,比命令行實用程序更適合於守護程序。

我可以推薦Inform 這是我所見過的唯一可以滿足這一需求的軟件包。 它提供了各種打印功能,可以在不同的情況下或使用不同的標題打印。 例如:

log()       -- prints to log file, no header
comment()   -- prints if verbose, no header
display()   -- prints if not quiet, no header
output()    -- always prints, no header
warning()   -- always prints with warning header
error()     -- always prints with error header
fatal()     -- always prints with error header, terminates program.

通知將這些功能稱為“通知人”。 通知者與Python打印功能非常相似,因為他們接受任意數量的參數並通過將它們連接在一起來構建消息。 它還允許您指定罪魁禍首 ,該罪魁禍首已添加到郵件的開頭。

例如,這是一個使用Inform編寫的簡單搜索和替換程序。

#!/usr/bin/env python3
"""
Replace a string in one or more files.

Usage:
    replace [options] <target> <replacement> <file>...

Options:
    -v, --verbose            indicate whether file is changed
"""

from docopt import docopt
from inform import Inform, comment, error, os_error
from pathlib import Path

# read command line
cmdline = docopt(__doc__)
target = cmdline['<target>']
replacement = cmdline['<replacement>']
filenames = cmdline['<file>']
Inform(verbose=cmdline['--verbose'], prog_name=True)

for filename in filenames:
    try:
        filepath = Path(filename)
        orig = filepath.read_text()
        new = orig.replace(target, replacement)
        comment('updated' if orig != new else 'unchanged', culprit=filename)
        filepath.write_text(new)
    except OSError as e:
        error(os_error(e))

Inform()用於指定您的首選項; comment()和error()是通知者,它們實際上是打印消息; 和os_error()是有用的實用程序,可將OSError異常轉換為可用作錯誤消息的字符串。

如果要運行此命令,則可能會得到以下輸出:

> replace -v tiger toe eeny meeny miny moe
eeny: updated
meeny: unchanged
replace error: miny: no such file or directory.
replace error: moe: no such file or directory.

希望這使您對Inform的功能有所了解。 那里有更多的力量。 例如,它提供了一些實用程序集合,這些實用程序在打印消息時很有用。 一個示例是os_error(),但還有其他示例。 您還可以定義自己的線人,這是處理多個詳細級別的一種方式。

import logging
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s') 

上面指定的level控制輸出的詳細程度。

您可以將處理程序(在我的案例中,這是復雜性勝過好處)附加到日志記錄中,以將輸出發送到不同的位置( https://docs.python.org/2/howto/logging-cookbook.html#multiple-handlers -and-formatters ),但到目前為止我只需要命令行輸出即可。

要產生輸出,必須在記錄時指定它的詳細程度

logging.debug("This debug message will rarely appeal to end users")

我還沒有讀完您的最后一行,到那時答案似乎很明顯,而且我也沒有想到可以將單個basicConfig行描述為“過於復雜”。 當打印不足時,我只用了60%的時間。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM