title: How do I execute an arbitrary script in the context of my Django project?
body: <p>Sometimes I want to execute a file in the context of my Django project, just as if I were using the shell, but with the convenience of using a text editor.  This is mainly to try something out, or quickly prototype some functionality before putting it into a view, test, recurring task, or management command.  </p>
  
  <p>I know I can stick these lines at the top of my .py file and it'll run in the Django context:</p>
  
  <pre><code>import sys
  sys.path.append('/location/of/projet')
  from django.core.management import setup_environ
  import settings
  setup_environ(settings)
  </code></pre>
  
  <p>I thought it'd be easier to make a management command that takes on argument, a python module to run, and executes it in the Django environment.   Here's the 'runmodule' command I wrote:</p>
  
  <pre><code>from django.core.management.base import BaseCommand, CommandError
  
  class Command(BaseCommand):
      help = "Runs an arbitrary module, in the Django environment, for quick prototyping of code that's too big for the shell."
  
      def handle(self, *args, **options):
          if not args:
              return
          module_name = args[0]
  
          try:
              __import__(module_name)
          except ImportError:
              print("Unable to import module %s.  Check that is within Django's PYTHONPATH" % (module_name))
  </code></pre>
  
  <p>This looks like it works -- I can stick some code in a module, and pass it as an argument to this command, and it'll get executed, e.g.</p>
  
  <pre><code>python manage.py runmodule myapp.trysomethingout
  </code></pre>
  
  <p>which will execute myapp/trysomethingout.py.  Is this the best way to do this?</p>