【问题标题】:ConfigParser writing double sections in output fileConfigParser 在输出文件中写入双节
【发布时间】: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


    【解决方案1】:

    这个bug是两次造成的

    config.write(cnf_file)
    cnf_file.close()
    

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

    您必须提取它们并将它们放在主文件中,或者更简单地,第二次以写入模式打开文件:

    cnf_file = open(config_file, 'w+')

    【讨论】:

      【解决方案2】:

      重新考虑布局。

      • 为什么你是 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)
      

      【讨论】:

        猜你喜欢
        • 2010-11-11
        • 2011-10-01
        • 1970-01-01
        • 1970-01-01
        • 2014-10-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多