本文整理汇总了Python中monitor.Monitor.start方法的典型用法代码示例。如果您正苦于以下问题:Python Monitor.start方法的具体用法?Python Monitor.start怎么用?Python Monitor.start使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类monitor.Monitor
的用法示例。
在下文中一共展示了Monitor.start方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_stop_personal_cloud
# 需要导入模块: from monitor import Monitor [as 别名]
# 或者: from monitor.Monitor import start [as 别名]
def test_stop_personal_cloud(self):
monitor = Monitor(self.personal_cloud)
print "try stop stop"
monitor.start()
# time.sleep(5)
monitor.stop()
示例2: main
# 需要导入模块: from monitor import Monitor [as 别名]
# 或者: from monitor.Monitor import start [as 别名]
def main():
# sleep(5) #added a sleep to avoid "Connection refused" or "404" errors
parser = argparse.ArgumentParser()
parser.add_argument('dir', help='the directory of the example')
args = parser.parse_args()
# locate config file
base_path = os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)),"..","examples",args.dir,"config"))
config_file = os.path.join(base_path, "sdx_global.cfg")
# locate the monitor's flows configuration file
monitor_flows_file = os.path.join(base_path, "monitor_flows.cfg")
config = Config(config_file)
# start umbrella fabric manager
logger = util.log.getLogger('monitor')
logger.info('init')
try:
with file(monitor_flows_file) as f:
flows = json.load(f)
except IOError:
flows = None
logger.info("No file specified for initial flows.")
logger.info('REFMON client: ' + str(config.refmon["IP"]) + ' ' + str(config.refmon["Port"]))
client = RefMonClient(config.refmon["IP"], config.refmon["Port"], config.refmon["key"])
controller = Monitor(config, flows, client, logger)
logger.info('start')
controller.start()
示例3: monitor_torrent
# 需要导入模块: from monitor import Monitor [as 别名]
# 或者: from monitor.Monitor import start [as 别名]
def monitor_torrent():
"""
Monitoring remote transmission status
"""
print (green('Monitoring remote transmission status.'))
monitor = Monitor()
monitor.start()
monitor.join()
示例4: test_emit_metric_to_manager
# 需要导入模块: from monitor import Monitor [as 别名]
# 或者: from monitor.Monitor import start [as 别名]
def test_emit_metric_to_manager(self):
monitor = Monitor(personal_cloud=self.personal_cloud, hostname=socket.gethostname())
print "try emit metric to manager"
monitor.start()
monitor.emit()
monitor.stop()
示例5: main
# 需要导入模块: from monitor import Monitor [as 别名]
# 或者: from monitor.Monitor import start [as 别名]
def main():
# init parser
parser = SafeConfigParser()
parser.read('../config/api.ini')
queue = Queue.Queue()
# get API entry
if parser.has_section('API'):
try:
base_url = parser.get('API', 'base_url')
testing_key = parser.get('API', 'testing_key')
production_key = parser.get('API', 'production_key')
except ConfigParser.NoOptionError as e:
print "Something missing in API config: " + e.message
return
else:
print "API section missing in config"
return
# loop over config and pass oeffis to workers
parser = SafeConfigParser()
parser.read('../config/oeffis.ini')
threads = []
for section_name in parser.sections():
# must be in config
try:
name = parser.get(section_name, "name")
rbl = parser.get(section_name, "rbl")
time_from = parser.get(section_name, "time_from")
time_to = parser.get(section_name, "time_to")
# time conversion
time_from = datetime.datetime.strptime(time_from, "%H:%M:%S.%f").time()
time_to = datetime.datetime.strptime(time_to, "%H:%M:%S.%f").time()
active = parser.get(section_name, "active")
except ConfigParser.NoOptionError as e:
print "Something missing in " + section_name + " config:" + e.message
continue
# threading
if active == "1":
thread = Monitor(queue, base_url, testing_key, production_key, name, rbl, time_from, time_to)
thread.start()
threads.append(thread)
# led thread
thread = Led(queue)
thread.start()
threads.append(thread)
# join queue
queue.join()
# join threads
for t in threads:
t.join()
print "Exiting rando. All threads stopped."
示例6: f2bcDaemon
# 需要导入模块: from monitor import Monitor [as 别名]
# 或者: from monitor.Monitor import start [as 别名]
class f2bcDaemon(daemon):
def __sigTERMhandler(self, signum, frame):
syslog.syslog ("Caught signal %d. Initiating shutdown..." % signum)
self.quit()
def run(self):
syslog.syslog ('fail2ban-zmq-tools Monitor starting.')
signal.signal(signal.SIGTERM, self.__sigTERMhandler)
signal.signal(signal.SIGINT, self.__sigTERMhandler)
self.monitor = Monitor(monitorconfig=monitorconfig)
syslog.syslog ('fail2ban-zmq-tools Monitor running. Main process waiting for termination signal. Threads working.')
self.monitor.start()
signal.pause()
syslog.syslog ('fail2ban-zmq-tools Monitor exiting.')
def quit(self):
syslog.syslog("fail2ban-zmq-tools Monitor received signal to quit.")
signal.signal(signal.SIGTERM,signal.SIG_IGN)
self.monitor.join()
示例7: FrontController
# 需要导入模块: from monitor import Monitor [as 别名]
# 或者: from monitor.Monitor import start [as 别名]
class FrontController(object):
"""
Error catching midleware. Intended to provide debug output - traceback.
If the exception is throwed with exc_info tuple as an additional argument
it is root cause and that is showed too.
"""
def __init__(self, controllers, **kw):
self._debug = kw.get('debug', False)
self._init_exc_info = None
self._worker = None
# TODO: following is shit...
#try:
if kw.has_key('loggers'):
for name, data in kw.get('loggers').items():
file = data.get('file')
fname = file.get('name')
size = file.get('size')
count = file.get('count')
set_logger(name, fname, max_bytes = size, backup_count = count)
if kw.has_key('exc_wrapper'):
exc_wrapper = kw.get('exc_wrapper')
log_setup = ExcInfoWrapper._logging
log_setup['init'] = exc_wrapper.get('init', log_setup['init'])
log_setup['call'] = exc_wrapper.get('call', log_setup['call'])
if kw.has_key('monitor'):
monitor = kw.get('monitor')
force_restart = monitor.get('force_restart', True)
self._monitor = Monitor(force_restart=force_restart)
for i in monitor.get('track_files', []):
self._monitor.track(i)
self._monitor.start()
#except:
# self._init_exc_info = ExcInfoWrapper()
if FrontControllerWorker is None:
self._init_exc_info = init_exc_info
else:
try:
self._worker = FrontControllerWorker(**controllers)
except:
self._init_exc_info = ExcInfoWrapper()
def __call__(self, environ, start_resp):
try:
try:
if self._worker is not None:
return self._worker(environ, start_resp)
else:
raise NotInitializedProperly('Front controller worker is missing.', exc_info = self._init_exc_info)
except HTTPOk:
raise HTTPInternalServerError('HTTPOk raised but not properly processed.', exc_info = True)
except HTTPRedirection:
exc_info = ExcInfoWrapper()
return exc_info(environ, start_resp, self._debug)
except HTTPError:
exc_info = ExcInfoWrapper()
return exc_info(environ, start_resp, self._debug)
except Exception:
raise HTTPInternalServerError('Exceptional state detected.', exc_info = True)
except HTTPError:
exc_info = ExcInfoWrapper()
return exc_info(environ, start_resp, self._debug)
示例8: Client
# 需要导入模块: from monitor import Monitor [as 别名]
# 或者: from monitor.Monitor import start [as 别名]
class Client(object):
INITIAL_TRACKERS=['udp://tracker.openbittorrent.com:80',
'udp://tracker.istole.it:80',
'udp://open.demonii.com:80',
'udp://tracker.coppersurfer.tk:80',
'udp://tracker.leechers-paradise.org:6969',
'udp://exodus.desync.com:6969',
'udp://tracker.publicbt.com:80']
VIDEO_EXTS={'.avi':'video/x-msvideo','.mp4':'video/mp4','.mkv':'video/x-matroska',
'.m4v':'video/mp4','.mov':'video/quicktime', '.mpg':'video/mpeg','.ogv':'video/ogg',
'.ogg':'video/ogg', '.webm':'video/webm', '.ts': 'video/mp2t', '.3gp':'video/3gpp'}
def __init__(self, url = None, port=None, ip=None, auto_shutdown=True, wait_time=20, timeout=5, auto_delete=True, temp_path=None, is_playing_fnc=None, print_status = False):
#server
if port:
self.port = port
else:
self.port = random.randint(8000,8099)
if ip:
self.ip = ip
else:
self.ip = "127.0.0.1"
self.server = Server((self.ip,self.port), Handler, client=self)
#Options
if temp_path:
self.temp_path = temp_path
else:
self.temp_path = os.path.join(os.path.dirname(__file__),"tmp")
self.is_playing_fnc = is_playing_fnc
self.timeout = timeout
self.auto_delete = auto_delete
self.wait_time= wait_time
self.auto_shutdown = auto_shutdown
self.buffer_size = 15
self.last_pieces_priorize = 5
self.state_file="state"
self.torrent_paramss={'save_path':self.temp_path,'storage_mode':lt.storage_mode_t.storage_mode_sparse}
#State
self.has_meta = False
self.meta = None
self.start_time = None
self.last_connect = 0
self.connected = False
self.closed = False
self.file = None
self.files = None
self._th=None
#Sesion
self._cache=Cache(self.temp_path)
self._ses=lt.session()
self._ses.listen_on(0,0)
#Cargamos el archivo de estado (si esxiste)
if os.path.exists(os.path.join(self.temp_path,self.state_file)):
try:
f = open(os.path.join(self.temp_path,self.state_file), "rb")
state=pickle.load(f)
self._ses.load_state(state)
f.close()
except:
pass
self._start_services()
#Monitor & Dispatcher
self._monitor= Monitor(self)
if print_status:
self._monitor.add_listener(self.print_status)
self._monitor.add_listener(self._check_meta)
self._monitor.add_listener(self.save_state)
self._monitor.add_listener(self.priorize_start_file)
self._monitor.add_listener(self.announce_torrent)
if self.auto_shutdown:
self._monitor.add_listener(self._auto_shutdown)
self._dispatcher=Dispatcher(self)
self._dispatcher.add_listener(self._update_ready_pieces)
#Iniciamos la URL
if url:
self.start_url(url)
def get_play_list(self):
"""
Función encargada de generar el playlist
"""
#Esperamos a lo metadatos
while not self.has_meta:
time.sleep(1)
#Comprobamos que haya archivos de video
#.........这里部分代码省略.........
示例9: Mediaplat
# 需要导入模块: from monitor import Monitor [as 别名]
# 或者: from monitor.Monitor import start [as 别名]
class Mediaplat(object):
""" Daemonize Class """
def __init__(self):
"""
Constructor of Daemon Class
"""
# register signal handlers
signal.signal(signal.SIGTSTP, signal.SIG_IGN)
signal.signal(signal.SIGTTIN, signal.SIG_IGN)
signal.signal(signal.SIGTTOU, signal.SIG_IGN)
signal.signal(signal.SIGINT, self.__signal_handler_terminate)
signal.signal(signal.SIGTERM, self.__signal_handler_terminate)
try:
self.server = ThreadedUnixSocketServer(SOCKET_FILE,
ThreadedUnixSocketRequestHandler)
except:
log.error('address already in use')
sys.exit(1)
def __signal_handler_terminate(self, signalnum, frame):
"""
Signal handler for terminate signals.
Signal handler for the "signal.SIGTERM" signal. Raise a "SystemExit"
exception to do something for that signal
"""
log.warning("Terminating on signal %(signalnum)r" % locals())
raise KeyboardInterrupt
def run(self, options):
"""
Beginning monitor thread.
Sleep and wait for interrupt.
"""
# Start plugin manager
plugin_manager.load_all_plugins()
# Start monitor thread
paths = settings.get('core', 'base').split(',')
content.set_push_func(plugin_manager.push_queue)
if options.rebuild:
content.rebuild()
self.monitor = Monitor(paths)
#self.monitor.set_push_queue_func(plugin_manager.push_queue)
self.monitor.start()
# Register bonjour
if settings.get('core', 'aggregation') == 'True':
self.bonjour = Bonjour()
self.bonjour.register(socket.gethostname(), '_mediaplat._tcp', 9020)
self.server.serve_forever()
def stop(self):
"""
stop the server and remove socket file.
Terminate all children threads and wait until terminate.
"""
try:
os.unlink(SOCKET_FILE)
except:
pass
if getattr(self, 'bonjour', None):
self.bonjour.unregister()
self.server.shutdown()
self.monitor.stop()
plugin_manager.stop()
def __enter__(self):
"""
Entry point of Daemon Class for python 'with' statement
"""
return self
def __exit__(self, exc_type, exc_value, traceback):
"""
Clean up function of Daemon Class for python 'with' statement
"""
self.stop()
@classmethod
def request(self, send_data, mode = 0):
""" request daemon function
@type send_data: dict
@param send_data: parameters related with service and action
@type mode: int
@param mode: request & response type
@rtype: dict
@return: {"error": int, "return_date": dict} dictionary
"""
try:
#.........这里部分代码省略.........
示例10: APIServer
# 需要导入模块: from monitor import Monitor [as 别名]
# 或者: from monitor.Monitor import start [as 别名]
#.........这里部分代码省略.........
(self.webroot + r"/comiclist", ComicListAPIHandler),
(self.webroot + r"/comic/([0-9]+)/page/([0-9]+|clear)/bookmark", ComicBookmarkAPIHandler ),
(self.webroot + r"/comic/([0-9]+)/page/([0-9]+)", ComicPageAPIHandler ),
(self.webroot + r"/comic/([0-9]+)/thumbnail", ThumbnailAPIHandler),
(self.webroot + r"/comic/([0-9]+)/file", FileAPIHandler),
(self.webroot + r"/entities(/.*)*", EntityAPIHandler),
(self.webroot + r"/folders(/.*)*", FolderAPIHandler),
(self.webroot + r"/command", CommandAPIHandler),
(self.webroot + r"/scanstatus", ScanStatusAPIHandler),
#(r'/favicon.ico', tornado.web.StaticFileHandler, {'path': os.path.join(AppFolders.appBase(), "static","images")}),
(self.webroot + r'/.*', UnknownHandler),
]
settings = dict(
template_path=os.path.join(AppFolders.appBase(), "templates"),
static_path=os.path.join(AppFolders.appBase(), "static"),
static_url_prefix=self.webroot + "/static/",
debug=True,
#autoreload=False,
login_url=self.webroot + "/login",
cookie_secret=self.config['security']['cookie_secret'],
xsrf_cookies=True,
)
tornado.web.Application.__init__(self, handlers, **settings)
if not opts.no_monitor:
logging.debug("Going to scan the following folders:")
for l in self.config['general']['folder_list']:
logging.debug(u" {0}".format(repr(l)))
self.monitor = Monitor(self.dm, self.config['general']['folder_list'])
self.monitor.start()
self.monitor.scan()
self.bookmarker = Bookmarker(self.dm)
self.bookmarker.start()
if opts.launch_browser and self.config['general']['launch_browser']:
if ((platform.system() == "Linux" and os.environ.has_key('DISPLAY')) or
(platform.system() == "Darwin" and not os.environ.has_key('SSH_TTY')) or
platform.system() == "Windows"):
webbrowser.open("http://localhost:{0}".format(self.port), new=0)
def rebuild(self):
# after restart, purge the DB
sys.argv.insert(1, "--_resetdb_and_run")
self.restart()
def restart(self):
self.shutdown()
executable = sys.executable
new_argv = ["--nobrowser"]
if self.opts.quiet:
new_argv.append("-q")
if self.opts.debug:
new_argv.append("-d")
if "--_resetdb_and_run" in sys.argv:
new_argv.append("--_resetdb_and_run")
if getattr(sys, 'frozen', None):
# only keep selected args
new_argv.insert(0, os.path.basename(executable) )
os.execv(executable, new_argv)
示例11: Client
# 需要导入模块: from monitor import Monitor [as 别名]
# 或者: from monitor.Monitor import start [as 别名]
class Client(object):
INITIAL_TRACKERS=['udp://tracker.openbittorrent.com:80',
'udp://tracker.istole.it:80',
'udp://open.demonii.com:80',
'udp://tracker.coppersurfer.tk:80',
'udp://tracker.leechers-paradise.org:6969',
'udp://exodus.desync.com:6969',
'udp://tracker.publicbt.com:80']
VIDEO_EXTS={'.avi':'video/x-msvideo','.mp4':'video/mp4','.mkv':'video/x-matroska',
'.m4v':'video/mp4','.mov':'video/quicktime', '.mpg':'video/mpeg','.ogv':'video/ogg',
'.ogg':'video/ogg', '.webm':'video/webm', '.ts': 'video/mp2t', '.3gp':'video/3gpp'}
def __init__(self, url = None, port=None, ip=None, auto_shutdown=True, wait_time=20, timeout=5, auto_delete=True, temp_path=None, is_playing_fnc=None, print_status = False):
#server
self.port = port if port else random.randint(8000,8099)
self.ip = ip if ip else "127.0.0.1"
self.server = Server((self.ip,self.port), Handler, client=self)
#Options
self.temp_path = temp_path if temp_path else os.path.join(os.path.dirname(__file__),"tmp")
self.is_playing_fnc = is_playing_fnc
self.timeout = timeout
self.auto_delete = auto_delete
self.wait_time= wait_time
self.auto_shutdown = auto_shutdown
self.buffer_size = 10
self.state_file="state"
self.torrent_paramss={'save_path':self.temp_path,'storage_mode':lt.storage_mode_t.storage_mode_sparse}
#State
self.has_meta = False
self.meta = None
self.start_time = None
self.last_connect = 0
self.connected = False
self.closed = False
self.file = None
self.files = None
self._th=None
#Sesion
self._cache=Cache(self.temp_path)
self._ses=lt.session()
self._ses.listen_on(0,0)
#Cargamos el archivo de estado (si esxiste)
if os.path.exists(os.path.join(self.temp_path,self.state_file)):
try:
with open(os.path.join(self.temp_path,self.state_file), "rb") as f:
state=pickle.load(f)
self._ses.load_state(state)
except:
pass
self._start_services()
#Monitor & Dispatcher
self._monitor= Monitor(self)
if print_status:
self._monitor.add_listener(self.print_status)
self._monitor.add_listener(self._check_meta)
self._monitor.add_listener(self.save_state)
self._monitor.add_listener(self.priorize_start_file)
self._monitor.add_listener(self.announce_torrent)
if self.auto_shutdown:
self._monitor.add_listener(self._auto_shutdown)
self._dispatcher=Dispatcher(self)
self._dispatcher.add_listener(self._update_ready_pieces)
#Iniciamos la URL
if url:
self.start_url(url)
def get_play_list(self):
#Esperamos a lo metadatos
while not self.has_meta:
time.sleep(1)
#Comprobamos que haya archivos de video
if self.files:
if len(self.files) > 1:
return "http://" + self.ip + ":" + str(self.port) + "/playlist.pls"
else:
return "http://" + self.ip + ":" + str(self.port) + "/" + urllib.quote(self.files[0].path)
def get_files(self):
#Esperamos a lo metadatos
while not self.has_meta:
time.sleep(1)
files = []
#Comprobamos que haya archivos de video
if self.files:
#.........这里部分代码省略.........
示例12: main
# 需要导入模块: from monitor import Monitor [as 别名]
# 或者: from monitor.Monitor import start [as 别名]
def main(argv):
duration = parseArguments(argv)
monitor = Monitor()
monitor.start(duration)
示例13: KonfigTracker
# 需要导入模块: from monitor import Monitor [as 别名]
# 或者: from monitor.Monitor import start [as 别名]
class KonfigTracker(KXmlGuiWindow, Ui_MainWindow):
def __init__(self,app):
KXmlGuiWindow.__init__(self)
#Backend Initializations
self.app = app
self.InitApplication()
self.monitor = Monitor(app)
self.monitor.start()
# UI Initializations
self.setupUi(self)
self.setFixedSize(self.width(), self.height())
self.setMainMenuBar()
self.connectMainSignals()
#System Tray Settings
self.trayItem = KStatusNotifierItem("konfigtracker",self)
self.trayItem.setStandardActionsEnabled(True)
self.trayItem.setIconByPixmap(QIcon(":/data/tray.png"))
self.trayItem.setToolTip(QIcon(":/data/tray.png"), "KonfigTracker", "Snapshot and monitoring tool for kde4 settings")
#update the list for setting up the backupList widget
self.commitMap = {}
self.pathMap = {}
self.slotUpdateView()
self.treeView.setHeaderLabel("No snapshots selected")
def InitApplication(self):
if not os.access(db_path,os.F_OK):
os.mkdir(db_path)
createDatabase(db_path)
performBackup()
else:
performBackup()
def setMainMenuBar(self):
self.appMenuBar = self.menuBar()
#Adding File Menu
self.fileMenu = KActionMenu("File", self)
self.quitAction = KStandardAction.quit(self.app.quit, self.actionCollection())
self.importAction = KAction("Import Configurations", self)
self.exportAction = KAction("Export Configurations", self)
self.exportAction.setEnabled(False)
self.fileMenu.addAction(self.importAction)
self.fileMenu.addAction(self.exportAction)
self.separator1 = self.fileMenu.addSeparator()
self.fileMenu.addAction(self.quitAction)
self.appMenuBar.addMenu(self.fileMenu.menu())
#Backup Menu
self.backupMenu = KActionMenu("Backup", self)
self.tagSelection = KAction("Tag Selected", self)
self.tagSelection.setEnabled(False)
self.initConfig = KAction("Initialize", self)
self.backupMenu.addAction(self.initConfig)
self.backupMenu.addAction(self.tagSelection)
self.appMenuBar.addMenu(self.backupMenu.menu())
#Restore Menu
self.restoreMenu = KActionMenu("Restore", self)
self.restoreSelection = KAction("To Selected Snapshot", self)
self.restoreSelection.setEnabled(False)
self.restoreMenu.addAction(self.restoreSelection)
self.appMenuBar.addMenu(self.restoreMenu.menu())
#Help Menu
self.helpMenu = KHelpMenu(self, aboutData)
self.appMenuBar.addMenu(self.helpMenu.menu())
def connectMainSignals(self):
#SIGNALS for pushbuttons
self.connect(self.archiveButton, SIGNAL("clicked(bool)"), self.slotExportDatabase)
self.connect(self.restoreButton, SIGNAL("clicked(bool)"), self.slotPerformRestore)
self.connect(self.importButton, SIGNAL("clicked(bool)"), self.slotImportArchive)
#SIGNALS for view items
self.connect(self.monitor, SIGNAL("backupDone"), self.slotUpdateView)
self.connect(self.backupList, SIGNAL("itemClicked(QListWidgetItem*)"), self.slotUpdateTreeView)
self.connect(self.backupList, SIGNAL("itemClicked(QListWidgetItem*)"), self.slotEnableItems)
self.connect(self.treeView, SIGNAL("itemSelectionChanged()"), self.slotShowLog)
#SIGNALS for menu items
self.connect(self.restoreSelection, SIGNAL("triggered(bool)"), self.slotPerformRestore)
self.connect(self.exportAction, SIGNAL("triggered(bool)"), self.slotExportDatabase)
self.connect(self.tagSelection, SIGNAL("triggered(bool)"), self.slotTagCommit)
def slotEnableItems(self):
self.tagSelection.setEnabled(True)
self.exportAction.setEnabled(True)
self.restoreSelection.setEnabled(True)
self.archiveButton.setEnabled(True)
self.restoreButton.setEnabled(True)
def slotImportArchive(self):
pass
def slotUpdateTreeView(self):
#.........这里部分代码省略.........