如何处理Python中的配置变量?

0 投票
3 回答
1683 浏览
提问于 2025-04-16 14:26

我刚开始学习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'替换成一个类外的变量,以便更好地进行配置呢?

祝好,

3 个回答

0

你可以创建一个Python脚本,里面包含一些配置变量。比如,你可以把这些变量放在一个叫做config.py的文件里:

dbname = 'database.db'
...

然后在你的其他文件中使用这些配置:

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

你可以使用Python标准库里的ConfigParser模块。

2

或者,如果你想从命令行传入配置,可以使用 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
        #(...)

撰写回答