Using Django for Cli Tool

Using django for CLI tool

While django is primarily for web apps it has a powerful and easy to use ORM that can be used for CLI apps as well. To use django script as a standalone script without a webserver, all you need to do is to add the following to the top of the file.

import os, sys
if __name__ == '__main__':
# Setup environ
sys.path.append(os.getcwd())
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "main.settings")

# Setup django
import django
django.setup()

# now you can import your ORM models

django and calling cli java application

In Python you can run other programs using module subprocess and read/write from their standard output/input. More complex CLI (command-line) applications can be controlled with pexpect. Of course you can set environment variable CLASSPATH.

If you want to run other programs in a web app (Django), make sure it will not make your users waiting for the HTML page for too long.

How to execute a Python script from the Django shell?

The << part is wrong, use < instead:

$ ./manage.py shell < myscript.py

You could also do:

$ ./manage.py shell
...
>>> execfile('myscript.py')

For python3 you would need to use

>>> exec(open('myscript.py').read())


Related Topics



Leave a reply



Submit