使用Python更改Linux主机名
我正在尝试通过一个Python程序来更改Linux的主机名。这个程序会从一个文件中随机选择一个名字,然后把这个名字设置为主机名。不过,代码只在随机数字值为1的时候才能正常工作。我哪里出错了呢?下面是我使用的代码。
import random
import os
import socket
contents=[]
with open("/root/Desktop/names.txt") as rnd:
for line in rnd:
line=line.strip()
contents.append(line)
name = contents[random.randint(0,len(contents)-1)]
rnd.close()
name = "hostname -b "+name
os.system(name)
hostname = socket.gethostname()
print "Hostname:", hostname
1 个回答
2
这个 random
模块提供了一个功能,可以从一个序列中随机选择一个元素:
name = random.choice(contents)
这正是你想要的功能。我觉得它还有一个好处,就是如果 contents
由于某种原因是空的,它会抛出一个异常。
更新:
顺便提一下,你不需要调用 rnd.close()
,因为你在一开始打开文件的时候使用了上下文管理器(with open(...) as rnd:
),当你离开 with
的范围时,它会自动关闭。