在后台运行python服务器
我正在使用将实时数据从python脚本推送到浏览器。但是,我希望它能够从解释器交互地工作,以便服务器能够继续在后台运行。一些伪代码:在后台运行python服务器,python,Python,我正在使用将实时数据从python脚本推送到浏览器。但是,我希望它能够从解释器交互地工作,以便服务器能够继续在后台运行。一些伪代码: #start server with the application and keep it running on the background server_inst=MyAppServer() #send data to the sever that pushes it to a browser (prints "foo" to the browser) s
#start server with the application and keep it running on the background
server_inst=MyAppServer()
#send data to the sever that pushes it to a browser (prints "foo" to the browser)
server_inst.send_data('foo')
看了线程技术之后,我仍然不知道该怎么做。任何提示。是否有理由将服务器和控制台程序作为同一进程 如果不是,我建议使用两个单独的进程和命名管道。如果此解决方案因任何原因不理想,请提供更多详细信息 无论如何,这里有一些代码可能对您实现管道类很有用。我不确定您需要通信的数据的具体形式是什么,这样您就可以使管道类抽象一些简单的协议和/或使用pickle
def __init__(self,sPath):
"""
create the fifo. if it already exists just associate with it
"""
self.sPath = sPath
if not os.path.exists(sPath):
try:
os.mkfifo(sPath)
except:
raise Exception('cannot mkfifo at path \n {0}'.format(sPath))
self.iFH = os.open(sPath,os.O_RDWR | os.O_NONBLOCK)
self.iFHBlocking = os.open(sPath,os.O_RDWR)
def base_read(self,iLen,blocking=False):
iFile = self.iFHBlocking if blocking else self.iFH
while not self.ready_for_reading():
import time
time.sleep(0.5)
lBytes = ''.encode('utf-8')
while len(lBytes)<iLen:
self.lock()
try:
lBytes += os.read(iFile,1)
self.unlock()
except OSError as e:
self.unlock()
if e.errno == 11:
import time
time.sleep(0.5)
else:
raise e
return lBytes
def base_write(self,lBytes,blocking = False):
iFile = self.iFHBlocking if blocking else self.iFH
while not self.ready_for_writing():
import time
time.sleep(0.5)
while True:
self.lock()
try:
iBytesWritten = os.write(iFile, lBytes)
self.unlock()
break
except OSError as e:
self.unlock()
if e.errno in [35,11]:
import time
time.sleep(0.5)
else:
raise
if iBytesWritten < len(lBytes):
self.base_write(lBytes[iBytesWritten:],blocking)
def get_lock_dir(self):
return '{0}_lockdir__'.format(self.sPath)
def lock(self):
while True:
try:
os.mkdir(self.get_lock_dir())
return
except OSError as e:
if e.errno != 17:
raise e
def unlock(self):
try:
os.rmdir(self.get_lock_dir())
except OSError as e:
if e.errno != 2:
raise e
def ready_for_reading(self):
lR,lW,lX = select.select([self.iFH,],[],[],self.iTimeout)
if not lR:
return False
lR,lW,lX = select.select([self.iFHBlocking],[],[],self.iTimeout)
if not lR:
return False
return True
def ready_for_writing(self):
lR,lW,lX = select.select([],[self.iFH,],[],self.iTimeout)
if not lW:
return False
return True
def\uuuuu init\uuuuuu(self,sPath):
"""
创建fifo。如果它已经存在,只需与它关联即可
"""
self.sPath=sPath
如果操作系统路径不存在(sPath):
尝试:
操作系统mkfifo(sPath)
除:
引发异常('无法在路径{0}处使用mkfifo'。格式(sPath))
self.iFH=os.open(sPath,os.O_RDWR | os.O_非块)
self.iFHBlocking=os.open(sPath,os.Ordwr)
def base_读取(自身、iLen、阻塞=错误):
iFile=self.iFHBlocking如果阻塞else self.iFH
而不是自己。准备好阅读了吗()
导入时间
睡眠时间(0.5)
lBytes=''.encode('utf-8')
而len(lBytes)