python读取配置文件
配置文件
cat >ini << EOF
[db]
db_host = 127.0.0.1
db_port = 3306
db_user = root
db_pass = root
host_port = 69
[concurrent]
thread = 10
processor = 20
[vnc]
db_host = 1.1.1.1
EOF
python代码
cat >config.py<<EOF
#!/usr/bin/env python
import ConfigParser
config = ConfigParser.ConfigParser()
config.read("ini")
print(config.sections())
r = config.options("db")
print(r)
r2 = config.get("db", "db_host")
print(r2)
r3 = config.items("db")
print(r3)
config.set("db","db_port","3306")
config.write(open("ini","w"))
#config.has_section("section")
#config.has_option("section", "option")
if not config.has_section("vnc"):
config.add_section("vnc")
if not config.has_option("vnc","db_host"):
config.set("vnc","db_host","1.1.1.1")
config.write(open("ini","w"))
EOF
执行代码
python config.py
['db', 'concurrent', 'vnc']
['db_host', 'db_port', 'db_user', 'db_pass', 'host_port']
127.0.0.1
[('db_host', '127.0.0.1'), ('db_port', '3306'), ('db_user', 'root'), ('db_pass', 'root'), ('host_port', '69')]