Как перенаправить stderr скрипта python3, используя тройник?

848
jlandercy

Я пользователь Debian и RedHat. Я хотел бы перенаправить stderr (модуль logging) из Python3скрипта. Сценарий выводит много вещей, и часть, которую я хочу захватить, может быть получена с помощью:

python3 ./script.py --input ./*.txt --verbose 2>> ./script.log 

Это добавляет stderr к ./script.log. Но я бы сохранил этот диалог и в терминале. Обычно я достигнуть этого трубопровода в teeкоманду. Проблема заключается в следующей shellстроке (выполняется из bashфайла):

pyhton3 ./script.py --input ./*.txt --verbose | tee -a ./script.log 

Выводит в терминал, но ничего не выводит ./script.log. Есть идеи, как поступить?

1

2 ответа на вопрос

2
John1024

To display both stdout and stderr on the terminal while only capturing stderr to file, use:

python3 ./script.py --input ./*.txt --verbose 2>&1 1>/dev/tty | tee -a script.log 

The way that the shell handles redirections is quite subtle. Here, the 2>&1 results in the command's stderr being piped to the tee command. 1>/dev/tty results in the command's stdout going directly to terminal. Order is important. If the order of these redirections is reversed, nothing would go to the pipe. Alternatively, if 1>/dev/tty were omitted, then both stdout and stderr would be piped to the tee command.

1
user2986553

You can redirect your stderr to stdout and then pipe it too tee like that

pyhton3 ./script.py --input ./*.txt --verbose 2>&1 | tee -a ./script.log

Похожие вопросы