【问题标题】:How to deal with configuration variables in Python?如何处理 Python 中的配置变量?
【发布时间】:2011-03-25 18:15:31
【问题描述】:

我是 Python 新手,我正在用它做一些测试。

我需要知道的是处理配置变量的最佳方式是什么。

例如,对于这段代码:

import twitter
import random
import sqlite3
import time
import bitly_api #https://github.com/bitly/bitly-api-python

class TwitterC:         
    def logtodatabase(self, tweet, timestamp):
        # Will log to the database
        database = sqlite3.connect('database.db') # Create a database file
        cursor   = database.cursor() # Create a cursor
        cursor.execute("CREATE TABLE IF NOT EXISTS twitter(id_tweet INTEGER AUTO_INCREMENT PRIMARY KEY, tweet TEXT, timestamp TEXT);") # Make a table
        # Assign the values for the insert into
        msg_ins       = tweet
        timestamp_ins = timestamp
        values        = [msg_ins, timestamp_ins]
        # Insert data into the table
        cursor.execute("INSERT INTO twitter(tweet, timestamp) VALUES(?, ?)", values)
        database.commit() # Save our changes
        database.close() # Close the connection to the database

在此代码中,如何将“database.db”替换为类外的变量,以获得更好的配置。 ?

最好的问候,

【问题讨论】:

    标签: python variables configuration


    【解决方案1】:

    或者如果你想从命令行传递配置,你可以使用argparse

    然后在创建 TwitterC 类时,你可以传入你想要的配置选项。

    class TwitterC:
        def __init__(self, database):
            self.database = database
        def logtodatabase(self, tweet, timestamp):
            # Will log to the database
            database = sqlite3.connect(self.database) # Create a database file
            #(...)
    

    【讨论】:

      【解决方案2】:

      您可以使用 Python 标准库之外的 ConfigParser

      【讨论】:

        【解决方案3】:

        您可以创建一个包含配置变量的 python 脚本: 配置文件:

        dbname = 'database.db'
        ...
        

        您的文件:

        import config
        database = sqlite3.connect(config.dbname)
        

        【讨论】:

          猜你喜欢
          • 2022-09-29
          • 1970-01-01
          • 2010-10-02
          • 1970-01-01
          • 1970-01-01
          • 2012-11-07
          • 1970-01-01
          • 2021-03-12
          • 1970-01-01
          相关资源
          最近更新 更多