python脚本 - 根据日志的运行方式将日志写入不同的地方

时间:2016-12-15 08:42:53

标签: python linux python-3.x

有没有办法让python脚本将日志写入2个不同的位置:文件和终端?但是如果我手动运行它,它应该只打印日志到终端。当Othwervise由其他东西运行时,它应该只将日志写入日志文件。它有可能吗?

1 个答案:

答案 0 :(得分:1)

如果程序连接到tty,则可以使用返回True的isatty()方法,否则返回False。因此,在您的情况下,您可以编写如下代码:

import sys

if sys.stdin.isatty():
   # Logs put here will be displayed on terminal when you invoke the script via cli
else:
    with open("/testFile.txt", "w") as f:
        f.write('Logging in a file')