[英]releasing modules with threaded classes and controlling them python
基本上,我正在构建一个具有几个编号选项供您选择的应用程序。
它名为main.py ,我为每个可能的选项编写了独立模块,因此我可以单独运行这些模块。 现在我写的这个模块包含一个线程类。 我执行命令时遇到的一个问题: python mod_keepOnline.py
是它不会将控制权传递回终端| AND |。 当我运行模块通过main.py时 , main.py停止监听新的选择。 我知道是因为线程。 我想知道如何“让线程在生成之后自行管理”。 因此,将控制权从mod_keepOnline.py
到终端或主脚本。
我还希望能够再次杀死已释放的线程。
像mod_keepOnline.py -killAll
东西
嗯,这是我的代码:
###########################################
################## SynBitz.net ############
import threading
import objects
import time
import mechanize
import os
import gb
##########################################
class Class_putOnline (threading.Thread):
def __init__ (self,person,onlineTime):
threading.Thread.__init__ (self)
self.startTime = time.time()
self.alive = True
self.person = person
self.onlineTime = onlineTime
self.firstMessage=True
def run(self):
while(self.alive):
if(self.firstMessage):
print self.person.getInfo() + " SPAWNED ONLINE"
self.firstMessage=False
self.person.login()
time.sleep(300)
self.person.logout()
if((time.time()-self.startTime) > self.onlineTime):
print self.person.getInfo() + " SPAWNED OFFLINE "
self.alive = False
self._Thread__stop()
#########################################
def main():
for line in open(gb.accFile,"r"):
gb.accountList.append(line.rstrip('\n'))
for account in gb.accountList:
gb.accountInfo = account.split('|',4)
browser = mechanize.Browser()
browser.set_handle_robots(False)
browser.set_handle_redirect(True)
browser.set_handle_referer(True)
browser.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')]
gb.spiderList.append(objects.spider.Bot(gb.accountInfo[0],gb.accountInfo[2],gb.accountInfo[1],gb.accountInfo[3],browser))
if gb.accountInfo[2] not in gb.distros:
gb.distros.append(gb.accountInfo[2])
onlineAccounts = []
for index, acc in enumerate(gb.spiderList):
onlineAccounts.append(Class_putOnline(acc,115200)) # 600*6*8*4= 28800 = 8 uur 3600 test seconds = 1 h (1200 seconds for test time of 20 minutes... )
time.sleep(0.1)
onlineAccounts[index].start()
if __name__ == "__main__":
main()
当我打开到服务器的ssh会话并运行python脚本时,即使我在后台运行它,在关闭会话后它也会死掉。 未连接时如何保持脚本运行?
当我打开到服务器的ssh会话并运行python脚本时,即使我在后台运行它,在关闭会话后它也会死掉。 未连接时如何保持脚本运行?
将其作为cronjob运行,如果需要按需运行脚本,请手动启动cronjob。
好吧,我是python的新手
我也是。
编辑:快速提示,使用“”“进行长注释。
例:
“““描述:
这样既可以做到这一点,又可以做到这一点。 这样使用它。
“”
我认为:
运行流程时,终端的输入和输出将重定向到流程的输入和输出。
如果您启动线程,这将不会对此进行任何更改。 只要两者都存在,则该过程具有终端输入和输出。 您可以做的是将此程序发送到后台(使用control-z)。
如果运行程序,则它具有自己的名称空间。 您可以导入一个模块并更改其属性,但这绝不会在另一个程序中更改该模块。
如果要有两个程序,一个在后台运行所有的例行程序(例如,泰森提议的作业),另一个从命令行运行,则需要在这两个进程之间进行通信。
也许还有其他方法可以绕过流程的边界,但我不知道它们。
因此,我编写了一个可以在其中存储值的模块。每次直接存储值时,模块的状态都会保存到磁盘。
'''
This is a module with persistent attributes
the attributes of this module are spread all over all instances of this module
To set attributes:
import runningConfiguration
runningConfiguration.x = y
to get attributes:
runningConfiguration.x
'''
import os
import types
import traceback
fn = fileName = fileName = os.path.splitext(__file__)[0] + '.conf'
class RunningConfiguration(types.ModuleType):
fileName = fn
def __init__(self, *args, **kw):
types.ModuleType.__init__(self, *args, **kw)
import sys
sys.modules[__name__] = self
self.load()
def save(self):
import pickle
pickle.dump(self.__dict__, file(self.fileName, 'wb'))
def load(self):
import pickle
try:
dict = pickle.load(file(self.fileName, 'rb'))
except EOFError:
pass
except:
import traceback
traceback.print_exc()
else:
self.__dict__.update(dict)
def __setattr__(self, name, value):
## print 'set', name, value,
l = []
v1 = self.__dict__.get(name, l)
self.__dict__[name] = value
try:
self.save()
## print 'ok'
except:
if v1 is not l:
self.__dict__[name] = v1
raise
def __getattribute__(self, name):
import types
if name in ('__dict__', '__class__','save','load','__setattr__', '__delattr__', 'fileName'):
return types.ModuleType.__getattribute__(self, name)
## print 'get', name
self.load()
l = []
ret = self.__dict__.get(name, l)
if ret is l:
if hasattr(self.__class__, name):
return getattr(self.__class__, name)
if name in globals():
return globals()[name]
raise AttributeError('%s object has no attribute %r' % (self.__class__.__name__, name))
return ret
def __delattr__(self, name):
del self.__dict__[name]
self.save()
RunningConfiguration(__name__)
我将其保存到runningConfiguration.py。
您可以像这样使用它:
# program1
import runningConfiguration
if not hasattr(runningConfiguration, 'programs'):
runningConfiguration.programs = [] ## variable programs is set
runningConfiguration.programs+= ['program1'] ## list is changed and = is used -> module is saved
这是一个不安全的模块,不是所有内容都可以保存到其中,而是包含很多内容。 同样,当两个模块同时保存时,第一个写入的值可能会丢失。
尝试一下:从两个不同的程序导入ist,并查看其行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.