运行 作为独立进程的服务器 - Python

Running a server as a standalone process - Python

我正在尝试将 Web 服务器 运行 作为测试框架中的独立进程:

from subprocess import Popen, PIPE, STDOUT
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By

server_cmd = "bundle exec thin start -p 3001 --ssl" # rails comamnd
# intend to start the server as a standalone process
webserver = Popen(server_cmd, shell=True, stdin=PIPE, stdout=PIPE,
                  stderr=PIPE, close_fds=True)

服务器运行良好,然后我执行一些 Selenium 任务。第一次,这些任务执行得很好:

 curl -v https://localhost:3001 -k
* Rebuilt URL to: https://localhost:3001/
*   Trying 127.0.0.1...
* Connected to localhost (127.0.0.1) port 3001 (#0)
* TLS 1.0 connection using TLS_RSA_WITH_AES_256_CBC_SHA
* Server certificate: openca.steamheat.net
> GET / HTTP/1.1
> Host: localhost:3001
> User-Agent: curl/7.43.0
> Accept: */*

但是一旦重复任务,网络服务器就会停止 运行:

curl -v https://localhost:3001 -k -L
* Rebuilt URL to: https://localhost:3001/
*   Trying 127.0.0.1...
* Connected to localhost (127.0.0.1) port 3001 (#0)
* Closing connection 0

当我在 shell 终端中执行相同的命令时,两个任务都按预期完成。 我想知道是否与 stdout 的输出量有关,因为 Rails 服务器向终端输出大量信息。 我该如何解决?网络服务器停止 运行 的原因是什么?

使用 stdin=PIPE, stdout=PIPE, stderr=PIPE,您实际上是在创建管道。一旦他们的缓冲区满了,他们就会阻塞。那时服务器将永远等待您的主进程读取它们。如果您不需要输出,只需执行 devnull = open(os.devnull, 'r+') 然后 stdin=devnull, ...。参数 close_fds=True 不会关闭 stdin、stdout 和 stderr。简而言之:

import os
devnull = open(os.devnull, 'r+')
webserver = Popen(server_cmd, shell=True, stdin=devnull,
                  stdout=devnull, stderr=devnull, close_fds=True)