Skip to main content
 首页 » 编程设计

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

2025年05月04日17pengyingh

我想用 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)