簡體   English   中英

如何從命令行運行django python文件

[英]how to run a django python file from command line

我有一個簡單的python文件,我最終想從chron運行。

它看起來像這樣:

from customers.models import Customer, NotificationLogEntry


def hello():
    customers =  Customer.objects.all()
    for c in customers:
        log_entry = NotificationLogEntry(
                                          customer=c,
                                          sent=True,
                                          notification_type=0,
                                          notification_media_type=0,
                                          )
        log_entry.save()


if __name__ == '__main__':
    hello()

當我運行這個:

python notifications.py

我收到導入錯誤:

Traceback (most recent call last):
  File "notifications.py", line 1, in <module>
    from customers.models import Customer, NotificationLogEntry
ImportError: No module named customers.models

這個模塊存在,我在我的django應用程序中沒有任何問題地調用它。 為什么我在應用程序之外收到此錯誤?

您可以創建自定義命令

https://docs.djangoproject.com/en/dev/howto/custom-management-commands/

或者,運行./manage.py shell然后導入您的文件

或者,加載django設置

http://www.b-list.org/weblog/2007/sep/22/standalone-django-scripts/

如果您正在運行cron作業,這是一個非常簡單的選項:

cat run.py | ./manage.py shell

你需要設置項目路徑

import os

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "your_project_name.settings")

# your imports, e.g. Django models
from customers.models import Customer, NotificationLogEntry

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM