crontab 某些命令有效,其他命令无效

crontab some commands works, others do not

总结

我有一个 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 中会出现一个新行,其中包含当前日期和时间。我也试过将测试脚本写入磁盘上的其他位置,它们似乎都有效。

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()

该工具现已成功运行!