Python 多进程 / 使用 cherrypy 的队列
我正在尝试用cherrypy写一个python代码。我的目标是从用户界面调用一个脚本,并在脚本生成日志时,将这些日志打印到用户界面上(比如在Iframe或div里)。
我使用的是CherryPy-3.2.4和Python 2.7。
以下是我写的示例代码,但它一直无法正常工作。
TestProcess.py
from multiprocessing import Process, Queue
import subprocess
import os, os.path
from string import Template
import cherrypy
from multiprocessing import Process, Queue
import HTML
import TestScript
class TestProcess(object):
PID=0
jquery_url = 'C:\CherryPy\TestScripts\jquery\jquery-1.11.1.js'
q=Queue()
@cherrypy.expose
def index(self):
html = """\
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> Test Doc </TITLE>
<script type="text/javascript" src="/static/jq/jquery-1.11.1.js"></script>
</HEAD>
<BODY>
<BR/>
<h3>Test utility</h3>
<form id="ping_form" target="console_iframe" method="post" action="/f">
<button id="ping" type="submit">Upgrade Installed Releases</button>
</form>
<BR/>
<iframe name="console_iframe" frameborder="1" width="1200"/>
</BODY>
</HTML>
"""
t = Template(html)
page = t.substitute(jquery_url=self.jquery_url)
return page
def f1():
print "*********** TEST **********************"
q.put([42, None, 'hello'])
@cherrypy.expose
def f(self, **kw):
q=Queue()
ts = TestScript.TestScript()
p = Process(target=ts.testCallFunction, args=(q,))
p.start()
#print q.get() # prints "[42, None, 'hello']"
p.join()
print "Test F"
def run_command():
# The yeilds here are the key to keeping things streaming
yield '<style>body {font-family: monospace;}</style>'
while(p.is_alive()):
while(not q.empty()):
yield q.get_nowait()
while(not q.empty()):
yield q.get_nowait()
return run_command()
if __name__ == '__main__':
conf = {
'/': {
'tools.sessions.on': True,
'tools.staticdir.root': os.path.abspath(os.getcwd())
},
'/static': {
'tools.staticdir.on': True,
'tools.staticdir.dir': './public'
}
}
q = Queue()
cherrypy.server.socket_host = '10.49.69.103'
cherrypy.config.update({
'log.screen':True,
'tools.sessions.on': True,
'checker.on':False
})
cherrypy.tree.mount(TestProcess(), config=None)
cherrypy.engine.start()
cherrypy.engine.block()
#cherrypy.quickstart(TestProcess(), '/', conf)
类 TestScript
class TestScript(object):
q=Queue()
def write_queue(self,data):
print "*********** TEST **********************"
scroll_to_bottom = '<script type="text/javascript">window.scrollBy(0,50);</script>'
if data == '\n':
self.q.put("\n<br />%s" % scroll_to_bottom) # include the iframe scroll fix
else:
self.q.put(data)
def testCallFunction(self, q):
#proc = subprocess.Popen(['python','CreateLog.py'],stdout=subprocess.PIPE)
cmd = subprocess.Popen(['python','CreateLog.py'], shell=True, stdout=subprocess.PIPE)
while True:
data = cmd.stdout.read(1) # Alternatively proc.stdout.read(1024)
if len(data) == 0:
break
self.write_queue(data) # sys.stdout.buffer.write(data) on Python 3.x
#print "*********** TEST **********************"
脚本 CreateLog.py
#filters output
import time
i = 0
while (i<=10):
print hex(i)*512
i += 1
time.sleep(0.5)
运行时出现的错误
[24/Jul/2014:16:59:10] ENGINE Bus STARTING
[24/Jul/2014:16:59:10] ENGINE Started monitor thread 'Autoreloader'.
[24/Jul/2014:16:59:10] ENGINE Started monitor thread '_TimeoutMonitor'.
[24/Jul/2014:16:59:15] ENGINE Error in 'start' listener <bound method Server.sta
rt of <cherrypy._cpserver.Server object at 0x01583390>>
Traceback (most recent call last):
File "c:\Python27\lib\site-packages\cherrypy\process\wspbus.py", line 197, in
publish
output.append(listener(*args, **kwargs))
File "c:\Python27\lib\site-packages\cherrypy\_cpserver.py", line 151, in start
ServerAdapter.start(self)
File "c:\Python27\lib\site-packages\cherrypy\process\servers.py", line 168, in
start
wait_for_free_port(*self.bind_addr)
File "c:\Python27\lib\site-packages\cherrypy\process\servers.py", line 412, in
wait_for_free_port
raise IOError("Port %r not free on %r" % (port, host))
IOError: Port 8080 not free on '10.49.69.103'
[24/Jul/2014:16:59:15] ENGINE Shutting down due to error in start listener:
Traceback (most recent call last):
File "c:\Python27\lib\site-packages\cherrypy\process\wspbus.py", line 235, in
start
self.publish('start')
File "c:\Python27\lib\site-packages\cherrypy\process\wspbus.py", line 215, in
publish
raise exc
ChannelFailures: IOError("Port 8080 not free on '10.49.69.103'",)
我哪里做错了?
2 个回答
0
端口8080被占用了,所以HTTP服务器无法在这个端口上工作。你可以试试输入 netstat -anpt
来查看哪个程序在使用这个端口,或者可以试试把“server.socket_port”改成8081或者其他没有被占用的端口。
2
请查看 16.6.3.2. Windows:
确保主模块可以被新的Python解释器安全地导入,而不会引起意外的副作用(比如启动一个新的进程)。
你没有在TestProcess.py的最后几行加上 if __name__ == '__main__':
这段代码,所以 Process
尝试去运行另一个服务器。