Python脚本修改Shell文件注释行失效,寻求技术解决方案
问题与解决方案
需求
需要对getweather.sh文件完成两个修改:
- 移除
#/home/pi/dew-heater/get-temp.py行开头的#,将其转为可执行行 - 给
python /home/pi/dew-heater/get-temp.py行添加开头的#,注释掉该行
当前getweather.sh相关内容:
Auto turn on/off dew heater based on auto or manual mode.python /home/pi/dew-heater/get-temp.py
原代码失效原因
你编写的两段Python代码均未生效,核心问题是当前文件中不存在#/home/pi/dew-heater/get-temp.py这一行,代码里的查找目标与实际文件内容不匹配,导致替换操作无任何效果。
正确实现代码
使用逐行处理的方式,精准匹配并修改目标行:
def modify_weather_script(): file_path = "/home/pi/dew-heater/getweather.sh" modified_lines = [] with open(file_path, 'r') as f: for line in f: stripped_line = line.strip() # 注释python开头的目标行 if stripped_line == "python /home/pi/dew-heater/get-temp.py": modified_lines.append(f"#{line}") # 取消注释带#的目标行 elif stripped_line == "#/home/pi/dew-heater/get-temp.py": modified_lines.append(line[1:]) else: modified_lines.append(line) with open(file_path, 'w') as f: f.writelines(modified_lines) modify_weather_script()
代码说明
- 逐行读取文件内容,避免一次性读取大文件的内存问题
- 对每一行做去空格匹配,确保不受行首行尾空格干扰
- 分别处理两种目标行,其他行保持原样
- 最后将修改后的内容写入原文件
内容的提问来源于stack exchange,提问作者BobW
相关产品推荐
相关产品推荐

