外部脚本和未应用的迁移

External script and unapplied migrations

我正在编写支持我的 Django 项目开发的脚本。首先,我想到为此目的使用 bash,但由于缺乏足够的知识和时间,我决定使用 argparse 和 运行ning 系统命令使用子进程编写一些东西。

一切顺利,直到我不得不 运行

./manage.py migrate

我通过 运行ning:

import subprocess
...
subprocess.Popen("python {} migrate".format(absolute_path_to_manage_py).split())

输出看起来没问题:

Operations to perform:
Apply all migrations: sessions, admin, auth, contenttypes, accounts, pcb
Running migrations:
Rendering model states... DONE
Applying contenttypes.0001_initial... OK
...
Applying sessions.0001_initial... OK    

它突然停止,但脚本仍然处于活动状态(它仍然是 运行ning),更糟糕的是,当我 运行 django 应用程序时,我收到一条消息,说我还有一些未应用的迁移。

我想我对 Python 中的 运行ning 系统命令或与 django 迁移相关的内容一无所知。

有什么提示可以解决这个问题吗?

来自subprocess docs

The recommended way to launch subprocesses is to use the following convenience functions. For more advanced use cases when these do not meet your needs, use the underlying Popen interface.

您可以使用 subprocess.call(),等待命令完成:

returncode = subprocess.call(["python", absolute_path_to_manage_py, "migrate"])

不使用子进程,您可以直接使用 call_command:

调用管理命令
from django.core.management import call_command

call_command('migrate')