Django запуск скрипта python

Как выполнить скрипт Python из оболочки Django?

my_script.py содержит несколько операций над одной из моих моделей Django. Я уже делал это раньше, но не могу вспомнить, как именно.

13 ответов

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

Для python3 вам нужно будет использовать

Для меня это выполняет только первую строку скрипта. Единственное, что работает, — это объединение обоих методов: ./manage.py shell

1.9.6 передает стандартный ввод в code.interact github.com/django/django/blob/1.9.6/django/core/management/… | docs.python.org/2/library/code.html Скорее всего, интерактивный характер разрушает вещи. Должна быть опция CLI shell для передачи стандартного ввода в eval .

Другое решение, которое работает как для Python 2.x, так и для 3.x, — echo ‘import myscript’ | python manage.py shell Я обнаружил, что это может быть полезно для быстрых и грязных сценариев, которые нужно запускать только один раз, без необходимости выполнять сложный процесс создания команды manage.py .

Вам не рекомендуется делать это с помощью shell — и это предназначено, поскольку вы не должны выполнять случайные скрипты из среды django (но есть способы обойти это, см. другие ответы).

Если это script, который вы будете запускать несколько раз, рекомендуется создать его как пользовательскую команду, т.е.

Читайте также:  Do all java classes extend object

для этого создайте файл в поддирете management и commands вашего app , то есть

my_app/ __init__.py models.py management/ __init__.py commands/ __init__.py my_command.py tests.py views.py 

и в этом файле определите свою пользовательскую команду (убедитесь, что имя файла — это имя команды, которую вы хотите выполнить из ./manage.py )

from django.core.management.base import BaseCommand class Command(BaseCommand): def handle_noargs(self, **options): # now do the things that you want with your models here 

Опять же, это лучший ответ. Начиная с django 1.8, NoArgsCommand устарела. На этой странице приведен рабочий пример: docs.djangoproject.com/en/1.9/howto/custom-management-commands/…

Согласно предыдущему комментарию, чтобы это работало для меня, мне нужно было изменить def handle_noargs(self, **options): def handle(self, **options):

Источник

Run Python Script in Django

You might occasionally need to run Python script in a Django project or shell when you have a new way that works with web development and Python. There are various approaches to doing this. In this post, we’ll examine the various Django methods for running Python scripts. Also, I have covered these points: –

  • How to run Python Script in Django Project using shell
  • How to run Python Script in Django using execfile
  • How to run Python Script in Django using extension package

Run Python Script in Django Project using shell

Let’s first understand what is Python Script.

A Python file meant to be executed immediately is referred to as a script. When you run it, it should act immediately. As a result, scripts frequently have code that was written outside the parameters of any classes or functions.

Run Python Script and Manage File are located in the same folder

Now, let’s learn to run Python Script in Django Project using the shell.

django-admin startproject MyProject
  • Now, create a python file (named “sample.py”) in the same folder in which the manage.py file of the Django project is located.
# Program to add two numbers # Define number num1 = 15 num2 = 26 # Add number result = num1 + num2 # Print result print('Sum of the two number:', result)

Here, we define num1 and num2 two variables having integer-type values. Next, we define the result variable that will add the num1 and num2 using the + operator. At last, the print() function is called to print the sum of the two numbers.

run python script in django

  • Type the below-given command to run the Python Script “sample.py” in the Django project using the shell.

python script using shell

This is how you run Python Script in Django Project using shell when Python Script and Manage File are located in the same folder.

Run Python Script and Manage File located in different folders

Now, let’s learn to run Python Script in Django Project using the shell.

django-admin startproject MyProject
# Program to multiple two numbers # Define number num1 = 23 num2 = 5 # Multiply number result = 23 * 5 # Print result print('Product of two number:'. result)

Here, we define num1 and num2 two variables having integer-type values. Next, we define the result variable that will multiply the num1 and num2 using the * operator. At last, the print() function is called to print the product of the two numbers.

  • Navigate to the Django project’s root folder, where the manage.py file is located.
  • Type the below-given command to run the Python Script “xyz.py” in the Django project using the shell.

python script in django using shell

This is how you run Python Script in Django Project using shell when Python Script and Manage File are not located in the same folder.

Run Python Script in Django using execfile

Let’s first understand what is execfile.

The execfile or exec is a python method that evaluates the contents of a file.

Now, let’s learn to run Python Script in Django Project using execfile.

django-admin startproject MyProject
# Python program to swap two variables # To take inputs from the user a = input('Enter value of x: ') b = input('Enter value of y: ') # create a temporary variable and swap the values temp = a a = b b = temp # Print the result print('The value of a after swapping: <>'.format(a)) print('The value of b after swapping: <>'.format(b)) 

Here, we define two variables called a and b that accept user input via the input() method. The value of the first variable, a, is then stored in the temporary variable temp.

The value of the second variable, b, is then assigned to variable a. Finally, by assigning variable b with the temporary variable temp for the given value, we finish this process of exchanging the value between two variables.

The swapped values are finally printed using the print() method.

  • Navigate to the Django project’s root folder, where the manage.py file is located.
  • Now, log into the Django shell by typing the below-given command.
  • Type the below-given command to run the Python Script “abc.py” in the Django project using execfile.
exec(open(''C:/Users/PythonGuides/Desktop/abc.py'').read()) 

python script suing exec 1

This is how you run Python Script in Django Project using exec when Python Script and Manage File are located in any location.

How to run Python Script in Django using extension package

Sometimes you have a new idea for web development, but we are not assured about that. That new idea can be any script including data loading, processing, and cleaning.

So, the ideal way to implement business logic is not usually to put it directly in views or models. At that moment, you can install Django extensions as a package that allows you to run the additional scripts.

Now, let’s learn to run Python Script in Django Project using an extension package.

  • As you know that Django extensions are a package that allows you to run additional scripts. You have to install it first by using a pip. Open a terminal window and type.
pip install django-extensions

install django extension

django-admin startproject Course
  • Create a Django app “Register”, within the Django project, by typing the below command in the terminal.
python manage.py startapp Register
  • Add the “djnago-extensions” package and “Register” app in the installed app list located in the settings.py file.

install django

  • By default, Django has a urls.py file under the project. Django recommends mapping the newly created app “Register” inside it.
from django.contrib import admin from django.urls import path, include urlpatterns = [ path("admin/", admin.site.urls), path('', include('Register.urls')) ] 
  • Create the Django models that define the fields and behaviors of the “Register” application data that we will be storing. Open the models.py file in the Django app and add the code below.
from django.db import models # Create your models here. class CourseRegister(models.Model): title = models.CharField(max_length = 500) author = models.CharField(max_length=200) def __str__(self): return self.author 

Here, we create the model class “CourseRegister” which has the following database fields.

  • title: The title of the blog post.
  • author: The person who has written the post.

And to change the display name of the object in the Django model use def __str__(self). It will render the author name as we return the self.author.

  • To register a model “CourseRegister” with the admin site, open the admin.py file and add the below-given code.
# Register your models here. from django.contrib import admin from .models import CourseRegister admin.site.register(CourseRegister)
  • To map the views, create an urls.py file under the app directory and add the below-given code inside it.
from django.urls import path from Register import views urlpatterns = [ path('', views.home, name='home'), ]
  • The views are Python functions or classes that receive a web request and return a web response. Add the below-given code in the views.py file inside the app directory.
from django.shortcuts import render # Create your views here. def home(): print('Hello') 
  • To create a migration for the model, use the below-given command. Inside the migration folder, a migration file will be created.
python manage.py makemigrations
python manage.py createsuperuser

run extra script admin

  • Create a scripts folder in the project directory to add the extra Python script.
  • Create __init__.py file in the scripts folder to indicate that scripts are also part of the Django project.
  • Create a new file “sample.py” that will contain the code that you need to execute. Add the below-given code in it.
from Register.models import CourseRegister def run(): result = CourseRegister.objects.all() print(result)

To get all the objects from the CourseRegister model before running the server we create this extra script having a function run.

python manage.py runscript sample

runscript in django

This is how you run Python Script in Django using the extension package.

You may also like to read the following Python Django tutorials.

Conclusion

In this article, we have learned three distinct approaches to running Python scripts from Django. Additionally, we have also covered the following topics.

  • How to run Python Script in Django Project using shell
  • How to run Python Script in Django using execfile
  • How to run Python Script in Django using extension package

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.

Источник

How to Run Python Script in Django Project

run python script from django

Sometimes you may need to execute a python script in Django shell or project. There are multiple ways to do this. In this article, we will look at the different ways to run python script in Django. This is very useful if you need to run python scripts for background tasks in your Django project. In many cases, web developers use this method to execute a python script in Django shell and run it as cron job to send automated messages and emails to their users.

How to Run Python Script in Django Project

Here are the different ways to run Python script, say, test.py in Django project. Most of the following commands use “./manage.py”. If they do not work for you, then please try the same commands with “sudo python ./manage.py” instead. This might happen because the Python PATH variable in your Linux system is not set.

1. Using shell

Navigate to the root folder of your Django project which contains manage.py file and run the python script using following command. We have assumed that manage.py and test.py are in same folders.

If your python script is in a different folder, you need to provide the full path to your python script. In the following example, our python script is located at /home/ubuntu/test.py

2. Using execfile

You may also log into Django shell first with the following command.

and then use execfile command to run the python script

In python 3+, you will need to use exec command instead of using execfile.

>>> exec(open('/home/ubuntu/test.py').read())

3. Using manage.py

You may also use manage.py alone to run python scripts as shown below.

$ ./manage.py /home/ubuntu/test.py

In this article, we have seen three different ways to run python scripts from Django shell. 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.

Источник

Оцените статью