自動シャットダウン
一定期間誰もログインしていなければシャットダウンするスクリプト。
code:python
from subprocess import check_output, check_call
from datetime import datetime
import sys
from pathlib import Path
def is_empty_dir(path):
for _ in path.iterdir():
return False
return True
def main() -> None:
data_dir = Path.home() / '.local' / 'share' / 'auto-shutdown'
data_dir.mkdir(parents=True, exist_ok=True)
datetime_file = data_dir / 'last-active-timestamp'
pause_dir = data_dir / 'pause'
outputs = check_output(('who',), encoding='utf8').splitlines()
outputs_without_tmux = tuple(line for line in outputs if 'tmux' not in line)
n = len(outputs_without_tmux)
now = datetime.now().timestamp()
threshold = 60 * 40
if n > 0 or (pause_dir.is_dir() and not is_empty_dir(pause_dir)):
with open(datetime_file, 'w') as f:
f.write(str(now))
return
try:
with open(datetime_file, 'r') as f:
d = float(f.read())
except Exception:
return
if now - d > threshold:
datetime_file.unlink()
check_call(('sudo', '/sbin/shutdown', '-h', 'now'))
if __name__ == '__main__':
main()
timedelta使えばよかった!