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

时间:2021-01-23 22:19:48

标签: python macos cron

总结

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

1 个答案:

答案 0 :(得分:0)

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

该工具现已成功运行!