检测是从控制台还是通过crontab运行python脚本 [英] Detect if python script is run from console or by crontab

查看:203
本文介绍了检测是从控制台还是通过crontab运行python脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象一下,脚本正在这两组条件"中运行:

Imagine a script is running in these 2 sets of "conditions":

  1. 实时操作,在sudo crontab
  2. 中设置
  3. 调试,当我从控制台./my-script.py
  4. 运行时
  1. live action, set up in sudo crontab
  2. debug, when I run it from console ./my-script.py

我想要实现的是自动检测调试模式",而无需我为脚本指定参数(例如--debug).

What I'd like to achieve is an automatic detection of "debug mode", without me specifying an argument (e.g. --debug) for the script.

是否有关于如何执行此操作的约定?是否有一个变量可以告诉我脚本所有者是谁?脚本是否在stdout处具有控制台?运行ps | grep确定吗?

Is there a convention about how to do this? Is there a variable that can tell me who the script owner is? Whether script has a console at stdout? Run a ps | grep to determine that?

谢谢您的时间.

推荐答案

由于sys.stdin将是 TTY 在调试模式下,您可以使用 os.isatty()函数:

Since sys.stdin will be a TTY in debug mode, you can use the os.isatty() function:

import sys, os
if os.isatty(sys.stdin.fileno()):
    # Debug mode.
    pass
else:
    # Cron mode.
    pass

这篇关于检测是从控制台还是通过crontab运行python脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆