简体   繁体   English

使用代码运行 runserver 命令

[英]Make the runserver command run with code

I want to start a server with the manage.py runserver command and I'm trying for some time now but don't really find the right way.我想用 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')

Everytime I start the test it seems like the process is starting in background but as soon as the browser window pops up it shows me a "can't connect" error.每次我开始测试时,进程似乎都在后台启动,但是一旦浏览器窗口弹出,它就会显示“无法连接”错误。 So the server is not running.所以服务器没有运行。

Please note that the test is working fine when I start the server myself.请注意,当我自己启动服务器时,测试工作正常。

This thing这东西

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

will simply wont work since you are running a shell command in Popen.由于您在 Popen 中运行 shell 命令,因此将无法正常工作。 When you do a Popen it tries to run the program specified with the arguments given.当您执行 Popen 时,它会尝试运行使用给定参数指定的程序。 You try to run cd but after it's done (and it probably failed since you are missing shell=True in the call to Popen) the process is closed, you cant write to its stdin, Popen doesnt open a shell (or a cmd instance in windows) it simply runs a program您尝试运行 cd 但在它完成后(并且它可能失败了,因为您在调用 Popen 时缺少 shell=True)该进程已关闭,您无法写入其标准输入, Popen 不会打开一个 shell(或一个 cmd 实例) windows)它只是运行一个程序

if you want to run your server do it directly:如果你想直接运行你的服务器:

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

I recommend you use LiveServerTestCase instead of TestCase for tests that use Selenium.对于使用 Selenium 的测试,我建议您使用LiveServerTestCase而不是TestCase Django will take care of starting and stopping the server, so you don't have to worry about it. Django 会负责启动和停止服务器,因此您不必担心。

For more information and an example of a test case that uses Selenium, see the docs .有关使用 Selenium 的测试用例的更多信息和示例,请参阅文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM