python - 为什么 django 自定义命令中导入的 python 脚本会覆盖 optparse 选项

标签 python django command optparse

我在 django 中有一个自定义命令,它调用另一个脚本,如下所示:

import script

from optparse import make_option
from django.core.management.base import BaseCommand

class Command(BaseCommand):

    option_list = BaseCommand.option_list + (
        make_option(
            "-f", 
            "--files", 
            dest = "files",
            help = "add files to list",
            action='store_true',
            default=False
        ),

        # Some more options here
    )

    def handle(self, *args, **options):
        script.main(files=options['files'])

我的自定义脚本也使用optparse。它看起来像这样。

from optparse import OptionParser

opts = OptionParser()
opts.add_option('-f', '--files', dest='files', action='store_true', default=false, help='file help message')
opts = opts.parse_opts()[0]

FILE = opts.file

def main(files=false):
    opts.files = files
    # Do the processing

现在,当我尝试运行命令 python manage.py command --option-other-than-file 时,它总是仅打印 --help 帮助消息> 和 --file 作为选项。此外,--files 选项的帮助消息是在导入脚本中定义的,而不是在命令文件中定义的。此外,当我尝试使用 python manage.py command --help 打印选项时,它显示相同的消息。似乎有些选项是如何被覆盖的。有人可以告诉我发生了什么事吗?谢谢。

编辑

这是 BaseCommand class 的代码

最佳答案

当您在命令中首次导入脚本时,它会执行script.py顶层的所有代码,包括opts.parse_opts()行。我认为 optparse 不应该允许在同一进程中进行两次这样的连续调用。

只需将 script.py optparse 部分移至 if __name__ == '__main__': 子句中,这样在将其用作模块时就不会触发,并且您应该没事。

关于python - 为什么 django 自定义命令中导入的 python 脚本会覆盖 optparse 选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17322341/

相关文章:

python - “int”对象没有属性 'strip' 错误消息

python - 如何捕获 str 异常?

python - 查询集注释中的动态字段名称

python - 在函数中迭代 Pandas 系列的行

python - Django 休息框架版本控制

python - linode 上的 gunicorn 无法启动

shell - 具有不同文件扩展名的ffmpeg图像concat文件

ffmpeg 视频编辑命令(以毫秒为单位)时间戳

linux - 找到 : invalid predicate when using -newermt

python - 为什么 Python 的日志记录模块不遵循 PEP8 约定?