crontab有些命令有效,有些则无效



摘要

我有一个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()

该工具现在已成功运行!

最新更新