找回密码
 注册
查看: 50|回复: 2

用Python写了个仿Mac的path_helper

[复制链接]
发表于 2025-11-8 14:46:40 | 显示全部楼层 |阅读模式
本帖最后由 rikhtdss 于 2025-11-8 14:55 编辑

Mac下有个path_helper命令,作用是将指定的目录添加到PATH变量中。原程序是用C写的,我模仿它的行为用Python重新与了一个。

用法:将脚本保存到

~/bin/path_helper
chmod +x .
mkdir ~/.config/paths.d

在 .profile 中加一句(如果希望添加PATH后立即生效,.bashrc里也加一句):

  1. eval `path_helper`
复制代码


以后遇到需要添加进 PATH 的目录,只需要 cd 到该目录底下运行命令

  1. echo `pwd` > ~/.config/paths.d/xxx
复制代码


path_helper.py

  1. #!/usr/bin/env python3

  2. import sys, os
  3. from pathlib import Path

  4. PATH_POOLS = ('/etc/paths.d', '$HOME/.config/paths.d')

  5. PATH_LIST = os.getenv('PATH').split(':')

  6. # Determine whether the given path needs to be expanded
  7. # (including other variables)
  8. def need_expand(p):
  9.     return '~' in p or '$' in p

  10. def expand_path(p):
  11.     e = os.path.expandvars(os.path.expanduser(p))
  12.     if need_expand(e):
  13.         return expand_path(e)
  14.     return e

  15. def usage():
  16.     print('usage: path_helper [-c | -s]', file=sys.stderr)


  17. def is_commented (ln):
  18.     return ln.strip()[0] == '#'

  19. def handle_file(aFile):
  20.     with open(expand_path(aFile)) as f:
  21.         for line in f:
  22.             if not is_commented(line):
  23.                 ln = expand_path(line.strip())
  24.                 if os.path.isdir(ln) and (ln not in PATH_LIST):
  25.                     PATH_LIST.insert(0, ln)

  26. def handle_dir(aDir, pattern='*'):
  27.     dir_path = Path(expand_path(aDir))

  28.     if dir_path.is_dir():
  29.         for file_path in dir_path.rglob(pattern):
  30.             if file_path.is_file():
  31.                 handle_file(file_path)
  32.    
  33. def main():
  34.     style = 'STYLE_SH'

  35.     argc = len(sys.argv)

  36.     if argc > 2:
  37.         usage()

  38.     shell = os.getenv('SHELL')

  39.     if 'csh' in shell:
  40.         style = 'STYLE_CSH'

  41.     if argc == 2:
  42.         if sys.argv[1] == '-c':
  43.             style = 'STYLE_CSH'
  44.         if sys.argv[1] == '-s':
  45.             style = 'STYLE_SH'
  46.         if sys.argv[1] == '-h' or sys.argv[1] == '--help':
  47.             usage()
  48.             exit(0)
  49.         
  50.     path_list = os.getenv('PATH').split(':')
  51.     for pool in PATH_POOLS:
  52.         handle_dir(pool)

  53.     newpath = ':'.join(PATH_LIST)

  54.     if style == 'STYLE_CSH':
  55.         print(f'setenv PATH "{newpath}"')
  56.     else:
  57.         print(f'PATH="{newpath}"; export PATH;')

  58. if __name__ == '__main__':
  59.     main()
复制代码
 楼主| 发表于 2025-11-8 14:51:52 | 显示全部楼层
延长笔记本电池寿命的Python脚本。原理很简单:充电到80%提醒停止充电,放电到20%提醒充电,避免过放。理论上可大幅延长笔记本电池使用寿命。

  1. #!/usr/bin/env python3

  2. import os
  3. from time import sleep

  4. SYS_PREFIX = '/sys/class/power_supply'
  5. MAX = 80
  6. MIN = 20
  7. WAIT = 3 * 60

  8. # 返回交流电的设备名及状态,True 表示接通,False 表示未接通
  9. def detect_ac_adapter():
  10.     for device in os.listdir(SYS_PREFIX):
  11.         device_path = os.path.join(SYS_PREFIX, device)
  12.         if os.path.isdir(device_path):
  13.             status_file = os.path.join(device_path, 'online')
  14.             if os.path.isfile(status_file):
  15.                 with open(status_file, 'r') as f:
  16.                     status = f.read().strip()
  17.                     return device, status == '1'
  18.                
  19. def detect_battery():
  20.     for device in os.listdir(SYS_PREFIX):
  21.         device_path = os.path.join(SYS_PREFIX, device)
  22.         if os.path.isdir(device_path):
  23.             status_file = os.path.join(device_path, 'capacity')
  24.             if os.path.isfile(status_file):
  25.                 with open(status_file, 'r') as f:
  26.                     return device, int(f.read().strip())
  27.     return None, None

  28. def send_notification(message):
  29.     os.system("notify-send '{}' '{}'".format('充电提醒', message))

  30. def performance_check():
  31.     ac_adapter, ac_online = detect_ac_adapter()
  32.     battery, capacity = detect_battery()
  33.     if battery and capacity <= MIN and (not ac_online):
  34.         send_notification(f'电量少于{MIN}%,请充电!')
  35.     if battery and capacity >= MAX and ac_online:
  36.         send_notification(f'电量大于{MAX}%,请移除外接电源!')
  37.    
  38. if __name__ == '__main__':
  39.     while True:
  40.         performance_check()
  41.         sleep(WAIT)
复制代码
回复

使用道具 举报

发表于 2025-11-11 21:31:27 | 显示全部楼层
我去,少见的谈技术的新贴
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

GMT+8, 2025-11-19 18:49 , Processed in 0.019237 second(s), 15 queries .

© 2001-2025 Discuz! Team. Powered by Discuz! X3.5.

快速回复 返回顶部 返回列表