简体   繁体   English

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

[英]Running a server as a standalone process - Python

I'm trying to have a webserver running as a standalone process inside my test framework: 我试图在我的测试框架中将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)

The server works out nicely, then I execute some Selenium tasks. 服务器运行良好,然后执行一些Selenium任务。 At the first time, those tasks execute nicely: 第一次,这些任务执行得很好:

 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: */*

However once the tasks is repeat, the webserver stops running: 但是,一旦重复执行任务,Web服务器将停止运行:

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

When I execute that same command in a shell terminal, both tasks finish as supposed. 当我在shell终端中执行同一命令时,两个任务均按预期完成。 I was wondering if there's something to do with the amount of output to stdout , since the Rails server outputs a lot of information to the terminal. 我想知道是否与stdout的输出量有关,因为Rails服务器会向终端输出很多信息。 How can I fix that? 我该如何解决? What are the reasons the webserver stops running? Web服务器停止运行的原因是什么?

With stdin=PIPE, stdout=PIPE, stderr=PIPE you essentially are creating pipes. 使用stdin=PIPE, stdout=PIPE, stderr=PIPE您实际上是在创建管道。 Once their buffers get full they will block. 一旦缓冲区满,它们将阻塞。 At that point the server will wait forever for your main process to read them. 届时,服务器将永远等待您的主进程读取它们。 If you do not need the output simply do devnull = open(os.devnull, 'r+') and then stdin=devnull, ... . 如果您不需要输出,只需执行devnull = open(os.devnull, 'r+') ,然后再执行stdin=devnull, ... The parameter close_fds=True will not close stdin, stdout and stderr. 参数close_fds=True将不会关闭stdin,stdout和stderr。 In short: 简而言之:

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

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

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