How to Execute a Python Script from the Django Shell

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

How to execute code in the Django shell by an external python script?

Firstly, you should not be accessing your Python shell with sudo. There's no need to be running as root.

Secondly, the way to create a script that runs from the command prompt is to write a custom manage.py script, so you can run ./manage.py deactivate_users. Full instructions for doing that are in the documentation.

Python script not working with django shell

Use exec(open("utility_folder/load_users.py").read()) into the shell instead of python3 manage.py shell < utility_folder/load_users.py.

Running a python commands from a python script in a python (Django) shell. Django

If you start your script the way you describe it you can just call the django DB API directly in your code:

Language.objects.create(language=language, text=text, campo=field)

How to schedule Django shell command every week?

That's exactly what the cron is for.

Instead of having separate python script create django command. Create your_app/commands/remove_db.py file.

from django.core.management.base import BaseCommand, CommandError

class Command(BaseCommand):
args = ''
help = 'Remove old database'

def handle(self, *args, **options):
# put your removal logic here

And then, in the command line:

$ python manage.py remove_db

Now, it's easy to add a new cron task to a Linux system, using crontab:

# m h  dom mon dow   command
0 0 * * 0 python /var/www/myapp/manage.py remove_db


Related Topics



Leave a reply



Submit