You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Debian 10下Python脚本修改hostname重启后失效求助

问题分析与解决

你的脚本问题出在没有正确关闭/刷新文件缓冲区。Python用open()写文件时,数据会先暂存到内存缓冲区,若没手动关闭或刷新,系统可能还没来得及把数据同步到磁盘就重启了,导致/etc/hostname实际是空的。而nano保存时会强制将数据写入磁盘,所以重启后能正常生效。

修复后的脚本

import os

hostname = input("hostname: ")
# 用with语句自动管理文件,会自动完成关闭和缓冲区刷新
with open('/etc/hostname', 'w') as file2:
    file2.write(hostname)
print("successfully")

reb = input("reboot?(y)")
if reb == "y":
    os.system("reboot")
else:
    print(":(")

额外说明

  • 不需要先执行rm /etc/hostname,open()的w模式会直接清空原有内容并写入新数据,多此一举还可能引发不必要的权限问题。
  • 如果坚持不用with语句,也可以手动调用方法确保数据写入磁盘:
file2 = open('/etc/hostname','w')
file2.write(hostname)
file2.flush()  # 强制把缓冲区数据同步到磁盘
file2.close()  # 关闭文件句柄

内容的提问来源于stack exchange,提问作者dmalin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 10:34:56