您可以使用此代码并更改您想要的每个命令,请注意,如果您运行此命令,您的 shell 必须在您的 django 项目文件夹中
如果需要,可以在 django run 命令之前使用“CD”命令改变方向
from subprocess import Popen
from sys import stdout, stdin, stderr
Popen('python manage.py runserver', shell=True, stdin=stdin, stdout=stdout ,stderr=stderr)
您可以通过此代码与 shell 通信:
from subprocess import Popen, PIPE
from sys import stdout, stdin, stderr
process = Popen('python manage.py createsuperuser', shell=True, stdin=PIPE, stdout=PIPE ,stderr=stderr)
outs, errs = process.communicate(timeout=15)
print(outs)
username="username"
process.stdin.write(username.encode('ascii'))
process.stdin.close
不幸的是,对于 createsuperuser,您会收到此错误:
由于未在 TTY 中运行,已跳过超级用户创建。你可以在你的项目中运行manage.py createsuperuser来手动创建一个
由于安全问题,您不能使用 tty 创建超级用户。
我更喜欢:
您可以在项目中使用此代码创建超级用户
from django.contrib.auth.models import User;
User.objects.create_superuser('admin', 'admin@example.com', 'pass')
如果您想使用 shell 创建超级用户,我建议您运行数据迁移 stackoverflow.com/a/53555252/9533909