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

时间:2022-11-18 23:18:34

I have a custom command in django which calls another script as follows:

我在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'])

My custom script also uses optparse. It looks something like this.

我的自定义脚本也使用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

Now when I try to run the command python manage.py command --option-other-than-file, it always prints the help message with only --help and --file as an option. Also the help message for --files option is the one defined in the import script and not in the command file. Also when I try printing the options using python manage.py command --help it shows the same message. It seems like some how the options are being overridden. can somebody tell me what's going on. Thanks.

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

Edit

Here is the code to the BaseCommand class

这是BaseCommand类的代码

1 个解决方案

#1


1  

When you first import script in your command it executes all the code at the top level of script.py, including the opts.parse_opts() line. I dont think optparse is supposed to allow for two such consecutive calls in a same process.

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

Just move your script.py optparse part in an if __name__ == '__main__': clause so it won't fire when using it as a module and you should be fine.

只需将你的script.py optparse部分移动到if __name__ =='__ main __':子句中,这样当它用作模块时它就不会触发,你应该没问题。

#1


1  

When you first import script in your command it executes all the code at the top level of script.py, including the opts.parse_opts() line. I dont think optparse is supposed to allow for two such consecutive calls in a same process.

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

Just move your script.py optparse part in an if __name__ == '__main__': clause so it won't fire when using it as a module and you should be fine.

只需将你的script.py optparse部分移动到if __name__ =='__ main __':子句中,这样当它用作模块时它就不会触发,你应该没问题。