在导入的模块中使用命令行参数

时间:2016-08-24 18:59:59

标签: python python-3.x argparse peewee

我的脚本download.py包含:

import argparse
import models

parser = argparse.ArgumentParser()
parser.add_argument("--db_path", required=True)

args = parser.parse_args()

models.py

import peewee

database = peewee.SqliteDatabase("wee.db")

class Artist(peewee.Model):
    name = peewee.CharField()

    class Meta:
        database = database

class Album(peewee.Model):
    artist = peewee.ForeignKeyField(Artist)
    title = peewee.CharField()
    release_date = peewee.DateTimeField()
    publisher = peewee.CharField()
    media_type = peewee.CharField()

    class Meta:
        database = database

而不是wee.db我想在args.db_path文件中使用download.py的数据库路径。我怎么能这样做?

2 个答案:

答案 0 :(得分:0)

您所要做的就是将您的arg传递给SqliteDatabase构造函数。

好像你正在使用Django。如果是这种情况,您可以(并且应该)在settings.pyas indicated on the docs.

中指定您的数据库

修改

这是一个代码示例,说明如何使用您建议的方式对现有代码执行此操作(我仍然认为有更好的方法):

models.py

database_name = "wee_db"

def set_database_name(name):
    database_name = name

database = peewee.SqliteDatabase(database_name)

download.py

models.set_database_name(args.db_path)

答案 1 :(得分:0)

这是一个可能的解决方案:

# download.py
import argparse
from models import DBManager

parser = argparse.ArgumentParser()
parser.add_argument("--db_path", required=True)

args = parser.parse_args()
DBManager(args.db_path)
# models.py
import peewee


class Artist(peewee.Model):
    name = peewee.CharField()


class Album(peewee.Model):
    artist = peewee.ForeignKeyField(Artist)
    title = peewee.CharField()
    release_date = peewee.DateTimeField()
    publisher = peewee.CharField()
    media_type = peewee.CharField()


class DBManager(object):

    def __init__(self, db_path):
        self.database = peewee.SqliteDatabase(db_path)

        Artist._meta.database = self.database
        Album._meta.database = self.database

        self.database.connect()
        self.database.create_tables([Artist, Album])