Running a Python script outside of Django

前端 未结 7 2065
后悔当初
后悔当初 2021-01-30 03:22

I have a script which uses the Django ORM features, amongst other external libraries, that I want to run outside of Django (that is, executed from the command-line).

Edi

7条回答
  •  野性不改
    2021-01-30 04:02

    Use runscript from django-extensions: python manage.py runscript

    In order to do this, you need to:

    1. pip install django-extensions
    2. Create a directory called scripts. This can be located in your root directory, or in a specific app.
    3. Initialize the directory with a blank init file:

      touch scripts/__init__.py

    4. Place your script in this directory, and include a run() function. Example:

      #hello.py
      
      def hello():
          return "Hello, World"
      
      def run():
          print hello()
      
    5. Run the script with python manage.py runscript hello

    Refer to docs and helpful blog post for more details.

提交回复
热议问题