gpt4 book ai didi

python - 使 runserver 命令与代码一起运行

转载 作者:太空宇宙 更新时间:2023-11-04 05:45:03 26 4
gpt4 key购买 nike

我想用 manage.py runserver 命令启动一个服务器,我已经尝试了一段时间,但没有真正找到正确的方法。

from subprocess import Popen, PIPE
from django.test import TestCase
import unittest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

class ExampleClass(TestCase):

def startServer(self):
process = Popen(['cd C:\mypath'], stdin=PIPE, stdout=PIPE)
process.stdin.write(['python', 'manage.py runserver'])

.
.
.
def test_examplename(self):
self.browser.get('http://localhost:8000')

每次我开始测试时,该过程似乎都在后台启动,但一旦弹出浏览器窗口,它就会向我显示“无法连接”错误。所以服务器没有运行。

请注意,当我自己启动服务器时,测试工作正常。

最佳答案

这件事

process = Popen(['cd C:\mypath'], stdin=PIPE, stdout=PIPE)
process.stdin.write(['python', 'manage.py runserver'])

将无法正常工作,因为您正在 Popen 中运行 shell 命令。当您执行 Popen 时,它会尝试运行使用给定参数指定的程序。你尝试运行 cd 但在它完成后(它可能失败了,因为你在调用 Popen 时缺少 shell=True)进程关闭,你不能写入它的标准输入,Popen 不打开 shell(或Windows 中的 cmd 实例)它只是运行一个程序

如果你想直接运行你的服务器:

process = Popen(['python, 'C:\mypath\manage.py', 'runserver'], stdin=PIPE, stdout=PIPE)

关于python - 使 runserver 命令与代码一起运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32585845/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com