0

Pythonにカスタムログ関数があり、入力を複数行に分割するPythonの方法が必要です。入力は、文字列、複数行の文字列、またはリストにすることができます。

これは文字列と複数行の文字列に適していますが、リストは処理しません。

def log( text, indent = 0):
    indent_level = 4
    current_time = str( datetime.datetime.now().time())[0:-3]
    for line in text.splitlines():
        log_line = current_time + ' | ' + indent_level * indent * ' ' + str( line)
        print( log_line)

複雑なことなくリストを処理できるようにするために何を提案しますか

if( type( string) == list):

あちこちでテストしますか?

4

1 に答える 1

1

メソッドの開始時に、ダックタイピングを使用して入力を一度正規化します。

try:
    # Assume you get multiline text
    lines = text.splitlines()
except AttributeError:
    # If your assumption was wrong, then you should already have a list
    lines = text
于 2012-12-17T18:14:49.420 に答える