【发布时间】:2014-06-08 04:24:52
【问题描述】:
我正在使用 ConfigParser 模块写出一个配置文件,其中包含正在收集的服务器信息。我写的第 1 部分是本地系统信息,但由于某种原因,它似乎将第 1 部分写了两次。
这是我用来编写配置的代码:
def system_info(config_file):
cnf_file = open(config_file, 'w+')
config.add_section('System Information')
wmi_conn_local = wmi.WMI()
for OpSys in wmi_conn_local.Win32_OperatingSystem():
OpSys = OpSys.Caption
x64 = tools.is_64_bit()
if x64 is True:
config.set('System Information', 'System Architecture', '64-bit')
else:
config.set('System Information', 'System Architecture', '32-bit')
HostName = socket.gethostname()
config.set('System Information', 'Hostname', HostName)
config.set('System Information', 'OS', OpSys)
config.write(cnf_file)
cnf_file.close()
def sql_info(config_file):
cnf_file = open(config_file, 'a+')
SQLServer_raw = raw_input("Please enter the SQL Server name: ")
server_correct = tools.query_yes_no("Is %s correct?" % SQLServer_raw)
if server_correct is False:
SQLServer_raw = raw_input("Sorry about that. Please enter the correct SQLCMD Path: ")
SQLIP = socket.gethostbyname(SQLServer_raw)
config.add_section('SQL Server')
config.set('SQL Server', 'Server Name', SQLServer_raw)
config.set('SQL Server', 'Server IP', SQLIP)
SQL_User = raw_input("Please enter the username to the connection to the SQL server: ")
user_correct = tools.query_yes_no("Is %s correct?" % SQL_User)
if user_correct is False:
SQL_User = raw_input("Sorry about that. Please enter the correct SQL User: ")
config.set('SQL Server', 'SQL User', SQL_User)
SQL_Pass = raw_input("Please enter the password for the username you specified above: ")
pass_correct = tools.query_yes_no("Is %s correct?" % SQL_Pass)
if pass_correct is False:
SQL_Pass = raw_input("Sorry about that. Please enter the correct SQL Password: ")
config.set('SQL Server', 'SQL Password', SQL_Pass)
config.write(cnf_file)
cnf_file.close()
if setup_exists is False:
os.system('cls')
print header
print "Setup file not found. Creating file."
logger.info("Setup file not found. Creating file.")
print "Gathering System Information..."
logger.info("Gathering System Information...")
setup_config.system_info(config_file)
print "Gathering SQL Server Information..."
logger.info("Gathering SQL Server Information...")
setup_config.sql_info(config_file)
这是我在配置文件中看到的输出:
[System Information]
system architecture = 64-bit
hostname = FLA-7MartinezD
os = Microsoft Windows 7 Enterprise
[System Information]
system architecture = 64-bit
hostname = FLA-7MartinezD
os = Microsoft Windows 7 Enterprise
[SQL Server]
server name = sql1
server ip = 198.105.244.102
sql user = sa
sql password = password
我唯一能看到的是,我使用 w+ 方法来编写系统信息,而 a+ 用于 SQL 部分(以及之后的其他部分)。我这样做是想先写 SysInfo,然后附加其他部分,但我可能错了。
【问题讨论】:
标签: python config configparser