【问题标题】:crontab some commands works, others do notcrontab 有些命令有效,有些则无效
【发布时间】:2021-04-28 02:16:18
【问题描述】:

总结

我有一个 python 脚本,可以将一行写入 sqlite3 数据库。我想用 crontab 运行它,但不能让它工作。

到目前为止我所做的尝试

crontab -l                
* * * * * /opt/homebrew/bin/python3 /Users/natemcintosh/dev/battery_condition/get_battery_condition.py 
* * * * * /opt/homebrew/bin/python3 /Users/natemcintosh/dev/battery_condition/testing_cron.py

第一个命令是附加到数据库行的命令。我可以在命令行复制并粘贴该命令,运行它,然后它会添加行。它确实不是每分钟运行一次。 /Users/natemcintosh/dev/battery_condition/get_battery_condition.py的内容是

# /Users/natemcintosh/dev/battery_condition/get_battery_condition.py
import subprocess
import re
import sqlite3
import datetime


def get_conds():
    # Run the command to get battery info
    command = "system_profiler SPPowerDataType".split()
    response = subprocess.run(command, check=True, capture_output=True)
    response = str(response.stdout)

    # Get just the parts of interest
    cycle_count = re.findall(r"Cycle Count: (\d+)", response)[0]
    condition = re.findall(r"Condition: (\w+)", response)[0]
    max_capacity = re.findall(r"Maximum Capacity: (\d+)", response)[0]
    now = str(datetime.datetime.now().isoformat())

    return [now, cycle_count, condition, max_capacity]


def append_row_to_db(db_name: str, items: list):
    conn = sqlite3.connect(db_name)
    with conn:
        conn.execute("INSERT INTO battery_condition VALUES (?,?,?,?)", items)
    conn.close()


if __name__ == "__main__":
    # Get the condition
    battery_condition = get_conds()

    # Append to the file
    filename = "/Users/natemcintosh/dev/battery_condition/battery_condition.db"
    append_row_to_db(filename, battery_condition)

第二个命令是一个可以工作的测试脚本。

#/Users/natemcintosh/dev/battery_condition/testing_cron.py
import datetime

if __name__ == "__main__":
    with open("/Users/natemcintosh/Desktop/crontest.txt", "a+") as f:
        now = str(datetime.datetime.now().isoformat())
        f.write(f"{now}\n")

每分钟,/Users/natemcintosh/Desktop/crontest.txt 中都会出现一个新行,其中包含当前日期和时间。我还尝试将测试脚本写入磁盘上的其他位置,它们似乎都可以工作。

【问题讨论】:

  • 首先,修复你的shebangs!每个脚本的第一行应该是#!(不仅仅是#),然后是解释器运行脚本的路径(不是脚本本身);类似#!/opt/homebrew/bin/python3。这可能无法解决它,所以接下来要做的是通过在 crontab 中的命令中添加类似 >>/tmp/get_battery_condition.log 2>&1 的内容来捕获脚本的输出和错误,并查看报告了哪些错误。我的猜测是 cron 下的环境中缺少一些东西,但需要更多信息来说明什么。
  • 嗨,戈登。你确实是对的!捕获日志中的错误表明,当 cron 调用它时,在路径上找不到 system_profiler 命令。添加可执行文件的完整路径解决了这个问题!非常感谢您的帮助!

标签: python macos cron


【解决方案1】:

Gordon Davisson 的帮助下,我找到了问题所在。当我调用subprocess.run(command, check=True, capture_output=True) 时,该命令没有可执行文件的完整路径。

曾经是

command = "system_profiler SPPowerDataType".split()

我得到了system_profiler 命令的完整路径

$ which system_profiler
/usr/sbin/system_profiler

并将我的 python 脚本中的行修复为

command = "/usr/sbin/system_profiler SPPowerDataType".split()

工具现在运行成功!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-29
    • 2012-02-04
    • 2014-10-05
    • 1970-01-01
    • 2020-04-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多