ConfigParser在输出文件中写入双节

时间:2014-06-08 04:24:52

标签: python config configparser

我正在使用ConfigParser模块写出包含正在收集的服务器信息的配置文件。我写的第一部分是本地系统信息,但似乎是出于某种原因两次写第一部分。

这是我用来编写配置的代码:

    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 +方法来编写系统Info,而是使用了一个用于SQL部分的a +(以及之后的其他部分)。我这样做是因为我想先写SysInfo,然后附上其他部分,但我可能错了。

2 个答案:

答案 0 :(得分:0)

该错误是由两次造成的

config.write(cnf_file)
cnf_file.close()

在两个被调用的函数中,config对象是全局的,然后第二次用cnf_file = open(config_file, 'a+')打开文件时你正在使用添加模式,所以添加了system_info的信息

你必须提取它们并将它们放在主文件中,或者更容易在写入模式下第二次打开文件:

cnf_file = open(config_file, 'w+')

答案 1 :(得分:0)

重新考虑布局。

  • 为什么config变量是全局的?
  • 你想让它成为全球性的吗?

您的问题是,配置对象是全局的,您将它写入文件两次!

  • 所以我要说你打电话给system_info(..)。
  • 配置对象现在包含一个部分"系统信息"
  • 您将配置写入文件:

    [System Information]
    system architecture = 64-bit
    hostname = FLA-7MartinezD
    os = Microsoft Windows 7 Enterprise 
    
  • 现在你调用sql_info()

  • 配置对象现在包含一个部分" SQL Server" "系统信息"
  • 您将配置附加到文件:

    [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
    

使用全局配置对象的解决方案

    def system_info():
        if not config.has_section('System Information'): # prevent DuplicateSectionError
            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)

    def sql_info():
        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)
        if not config.has_section('SQL Server'): # prevent DuplicateSectionError
            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)

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()

        print "Gathering SQL Server Information..."
        logger.info("Gathering SQL Server Information...")
        setup_config.sql_info()

        with open(config_file, 'w') as cnf_file:
            config.write(cnf_file)

使用本地配置对象的解决方案(推荐)

    def system_info(config):
        if not config.has_section('System Information'): # prevent DuplicateSectionError
            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)
        return config

    def sql_info(config):
        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)
        if not config.has_section('SQL Server'): # prevent DuplicateSectionError
            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)
        return config

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.")
        config = ConfigParser.RawConfigParser()
        print "Gathering System Information..."
        logger.info("Gathering System Information...")
        config = setup_config.system_info(config)

        print "Gathering SQL Server Information..."
        logger.info("Gathering SQL Server Information...")
        config = setup_config.sql_info(config)

        with open(config_file, 'w') as cnf_file:
            config.write(cnf_file)