Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running a Python script outside of Django

Tags:

python

django

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).

Edit: At the moment, I can launch it by navigating to a URL...

How do I setup the environment for this?

like image 655
geejay Avatar asked Aug 21 '09 07:08

geejay


People also ask

Can Django run python script?

Although it is not recommended to run python scripts from Django shell, this is a great way to run background tasks. This is because when you run python scripts from Django shell, it gives you access to all models, views and functions defined in your Django project.

How do I add a python file to Django project?

Just add it to the python path and thats it or is it a better way to go? If you place them in a folder you need to add a file called __init__.py to the folder. It can be empty. After that you should be able to import files from the folder.


2 Answers

The easiest way to do this is to set up your script as a manage.py subcommand. It's quite easy to do:

from django.core.management.base import NoArgsCommand, make_option  class Command(NoArgsCommand):      help = "Whatever you want to print here"      option_list = NoArgsCommand.option_list + (         make_option('--verbose', action='store_true'),     )      def handle_noargs(self, **options):         ... call your script here ... 

Put this in a file, in any of your apps under management/commands/yourcommand.py (with empty __init__.py files in each) and now you can call your script with ./manage.py yourcommand.

If you're using Django 1.10 or greater NoArgsCommand has been deprecated. Use BaseCommand instead. https://stackoverflow.com/a/45172236/6022521

like image 69
Daniel Roseman Avatar answered Sep 28 '22 08:09

Daniel Roseman


from <Project path>          import settings          #your project settings file from django.core.management  import setup_environ     #environment setup function  setup_environ(settings)  #Rest of your django imports and code go here 
like image 33
Fausto I. Avatar answered Sep 28 '22 08:09

Fausto I.