How to call django.setup() in console_script?
<p>The current django docs tell me this:</p>

<blockquote>
  <p>django.setup() may only be called once.</p>
  
  <p>Therefore, avoid putting reusable application logic in standalone scripts so that you have to import from the script elsewhere in your application. If you canât avoid that, put the call to django.setup() inside an if block:</p>
</blockquote>

<pre><code>if __name__ == '__main__':
    import django
    django.setup()
</code></pre>

<p>Source: <a href="https://docs.djangoproject.com/en/1.10/topics/settings/#calling-django-setup-is-required-for-standalone-django-usage">Calling django.setup() is required for âstandaloneâ Django usage</a></p>

<p>I am using entry points in setup.py. This way I don't have <code>__name__ == '__main__'</code>.</p>

<h1>Question</h1>

<p>How to ensure django.setup() gets only called once if you use <a href="http://python-packaging.readthedocs.io/en/latest/command-line-scripts.html#the-console-scripts-entry-point">console_scripts</a>?</p>

<p>Where should I put <code>django.setup()</code>?</p>

<h1>Background</h1>

<p>The actual error I have: Django hangs. Here is the reason: <a href="https://code.djangoproject.com/ticket/27176">https://code.djangoproject.com/ticket/27176</a></p>

<p>I want to port my application to the current django version. Changing to a management command is not an option, since other (third party applications) rely on the existence of my console scripts.</p>

<p>I have worked in two production CLI python packages with explicitly calling <code>django.setup()</code> in <code>console_scripts</code>. </p>

<p>The most important thing you should note is <code>DJANGO_SETTINGS_MODULE</code> in <code>env</code> path.</p>

<p>You can set this value in shell script or even load default settings in your python script.</p>

<p>Here is example:</p>

<pre><code># setup.py
entry_points={
    'my-cli = mypackage.cli:main'
}
</code></pre>

<p>.</p>

<pre><code># cli.py
import logging
from os import environ as env


if not 'DJANGO_SETTINGS_MODULE' in env:
    from mypackage import settings
    env.setdefault('DJANGO_SETTINGS_MODULE', settings.__name__)


import django
django.setup()

# this line must be after django.setup() for logging configure
logger = logging.getLogger('mypackage')

def main():
    # to get configured settings
    from django.conf import settings

    # do stuffs


if __name__ == '__main__':
    main()
</code></pre>

python django python-import hang