[英]Python - how can I run separate module (not function) as a separate process?
tl,dr: How can I programmably execute a python module (not function) as a separate process from a different python module? tl,dr:我如何以可编程的方式执行 python 模块(不起作用)作为与不同 python 模块的单独进程?
On my development laptop, I have a 'server' module containing a bottle server.在我的开发笔记本电脑上,我有一个包含瓶子服务器的“服务器”模块。 In this module, the name==main clause starts the bottle server.
在这个模块中,name==main 子句启动了 Bottle 服务器。
@bt_app.post("/")
def server_post():
<< Generate response to 'http://server.com/' >>
if __name__ == '__main__':
serve(bt_app, port=localhost:8080)
I also have a 'test_server' module containing pytests.我还有一个包含 pytests 的“test_server”模块。 In this module, the name==main clause runs pytest and displays the results.
在此模块中,name==main 子句运行 pytest 并显示结果。
def test_something():
_rtn = some_server_function()
assert _rtn == desired
if __name__ == '__main__':
_rtn = pytest.main([__file__])
print("Pytest returned: ", _rtn)
Currently, I manually run the server module (starting the web server on localhost), then I manually start the pytest module which issues html requests to the running server module and checks the responses.目前,我手动运行服务器模块(在 localhost 上启动 web 服务器),然后手动启动 pytest 模块,该模块发出 html 模块请求并检查对正在运行的服务器的响应。
Sometimes I forget to start the server module.有时我忘记启动服务器模块。 No big deal but annoying.
没什么大不了的,但很烦人。 So I'd like to know if I can programmatically start the server module as a separate process from the pytest module (just as I'm doing manually now) so I don't forget to start it manually.
所以我想知道我是否可以以编程方式将服务器模块作为与 pytest 模块分开的进程启动(就像我现在手动做的那样),所以我不会忘记手动启动它。
Thanks谢谢
There is my test cases dir tree:有我的测试用例目录树:
test
├── server.py
└── test_server.py
server.py
start a web server with flask. server.py
使用 flask 启动 web 服务器。
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
if __name__ == '__main__':
app.run()
test_server.py
make request to test. test_server.py
发出测试请求。
import sys
import requests
import subprocess
import time
p = None # server process
def start_server():
global p
sys.path.append('/tmp/test')
# here you may want to do some check.
# whether the server is already started, then pass this fucntion
kwargs = {} # here u can pass other args needed
p = subprocess.Popen(['python','server.py'], **kwargs)
def test_function():
response = requests.get('http://localhost:5000/')
print('This is response body: ', response.text)
if __name__ == '__main__':
start_server()
time.sleep(3) # waiting server started
test_function()
p.kill()
Then you can do python test_server
to start the server and do test cases.然后你可以做
python test_server
来启动服务器并做测试用例。
PS: Popen()
needs python3.5+. PS:Popen
Popen()
需要 python3.5+。 if older version, use run
instead如果版本较旧,请改用
run
import logging
import threading
import time
def thread_function(name):
logging.info("Thread %s: starting", name)
time.sleep(2)
logging.info("Thread %s: finishing", name)
if __name__ == "__main__":
format = "%(asctime)s: %(message)s"
logging.basicConfig(format=format, level=logging.INFO,
datefmt="%H:%M:%S")
threads = list()
for index in range(3):
logging.info("Main : create and start thread %d.", index)
x = threading.Thread(target=thread_function, args=(index,))
threads.append(x)
x.start()
for index, thread in enumerate(threads):
logging.info("Main : before joining thread %d.", index)
thread.join()
logging.info("Main : thread %d done", index)
With threading you can run multiple processes at once!使用线程,您可以一次运行多个进程!
Wim baasically answered this question. Wim基本上回答了这个问题。 I looked into the subprocess module.
我查看了子流程模块。 While reading up on it, I stumbled on the os.system function.
在阅读它时,我偶然发现了 os.system function。
In short, subprocess is a highly flexible and functional program for running a program.简而言之,子进程是一个用于运行程序的高度灵活和功能强大的程序。 os.system, on the other hand, is much simpler, with far fewer functions.
另一方面,os.system 要简单得多,功能要少得多。
Just running a python module is simple, so I settled on os.system.只运行一个 python 模块很简单,所以我选择了 os.system。
import os
server_path = "python -m ../src/server.py"
os.system(server_path)
Wim, thanks for the pointer.维姆,谢谢你的指点。 Had it been a full fledged answer I would have upvoted it.
如果这是一个完整的答案,我会赞成的。 Redo it as a full fledged answer and I'll do so.
重做一个完整的答案,我会这样做。
Async to the rescue.异步救援。
import gevent
from gevent import monkey, spawn
monkey.patch_all()
from gevent.pywsgi import WSGIServer
@bt_app.post("/")
def server_post():
<< Generate response to 'http://server.com/' >>
def test_something():
_rtn = some_server_function()
assert _rtn == desired
print("Pytest returned: ",_rtn)
sleep(0)
if __name__ == '__main__':
spawn(test_something) #runs async
server = WSGIServer(("0.0.0.0", 8080, bt_app)
server.serve_forever()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.