prompt
large_stringlengths 72
9.34k
| completion
large_stringlengths 0
7.61k
|
---|---|
<|file_name|>read_job.py<|end_file_name|><|fim▁begin|># JoeTraffic - Web-Log Analysis Application utilizing the JoeAgent Framework.
# Copyright (C) 2004 Rhett Garber
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
from JoeAgent import job, event
import db_interface
import os, os.path
import logging
import log_parser
LINEINCR = 30
log = logging.getLogger("agent.LogReader")
class ReadLogCompleteEvent(event.Event):
<|fim_middle|>
class ReadLogContinueEvent(event.Event):
"""Event to indicate we should continue reading the file. Log file
processing will be done in chunks so as not to block the agent for
too long."""
pass
class ReadLogJob(job.Job):
def __init__(self, agent_obj, logfile):
job.Job.__init__(self, agent_obj)
assert os.path.isfile(logfile), "Not a file: %s" % str(logfile)
self._log_size = os.stat(logfile).st_size
log.debug("Log size is %d" % self._log_size)
self._logfile_path = logfile
self._logfile_hndl = open(logfile, 'r')
self._progress = 0 # Data read from file
self._db = db_interface.getDB()
def getFilePath(self):
return self._logfile_path
def getBytesRead(self):
return self._progress
def getBytesTotal(self):
return self._log_size
def run(self):
evt = ReadLogContinueEvent(self)
self.getAgent().addEvent(evt)
def notify(self, evt):
job.Job.notify(self, evt)
if isinstance(evt, ReadLogContinueEvent) and evt.getSource() == self:
log.debug("Continuing read of file")
# Continue to read the log
try:
self._progress += log_parser.read_log(
self._logfile_hndl, self._db, LINEINCR)
log.debug("Read %d %% of file (%d / %d)" % (self.getProgress(),
self._progress,
self._log_size))
except log_parser.EndOfLogException, e:
self._progress = self._log_size
# Log file is complete, updated the db entry
self._mark_complete()
# Add an event to notify that the file is complete
self._logfile_hndl.close()
new_evt = ReadLogCompleteEvent(self)
self.getAgent().addEvent(new_evt)
except log_parser.InvalidLogException, e:
log.warning("Invalid log file: %s" % str(e))
self._logfile_hndl.close()
new_evt = ReadLogCompleteEvent(self)
self.getAgent().addEvent(new_evt)
else:
# Add an event to continue reading
new_evt = ReadLogContinueEvent(self)
self.getAgent().addEvent(new_evt)
def _update_db(self):
"""Update the entry in the database for this logfile"""
log.debug("Updating file %s" % self._logfile_path)
pass
def _mark_invalid(self):
"""Update the database to indicate that this is not a valid log file"""
log.debug("Marking file %s invalid" % self._logfile_path)
pass
def _mark_complete(self):
log.debug("Marking file %s complete" % self._logfile_path)
pass
def getProgress(self):
"""Return a percentage complete value"""
if self._log_size == 0:
return 0
return int((float(self._progress) / self._log_size) * 100)
<|fim▁end|> | """Event to indicate the file is completely read. This event will
be caught by the FindLogJob that is watching it. The file will
continue to be checked for modifications"""
pass |
<|file_name|>read_job.py<|end_file_name|><|fim▁begin|># JoeTraffic - Web-Log Analysis Application utilizing the JoeAgent Framework.
# Copyright (C) 2004 Rhett Garber
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
from JoeAgent import job, event
import db_interface
import os, os.path
import logging
import log_parser
LINEINCR = 30
log = logging.getLogger("agent.LogReader")
class ReadLogCompleteEvent(event.Event):
"""Event to indicate the file is completely read. This event will
be caught by the FindLogJob that is watching it. The file will
continue to be checked for modifications"""
pass
class ReadLogContinueEvent(event.Event):
<|fim_middle|>
class ReadLogJob(job.Job):
def __init__(self, agent_obj, logfile):
job.Job.__init__(self, agent_obj)
assert os.path.isfile(logfile), "Not a file: %s" % str(logfile)
self._log_size = os.stat(logfile).st_size
log.debug("Log size is %d" % self._log_size)
self._logfile_path = logfile
self._logfile_hndl = open(logfile, 'r')
self._progress = 0 # Data read from file
self._db = db_interface.getDB()
def getFilePath(self):
return self._logfile_path
def getBytesRead(self):
return self._progress
def getBytesTotal(self):
return self._log_size
def run(self):
evt = ReadLogContinueEvent(self)
self.getAgent().addEvent(evt)
def notify(self, evt):
job.Job.notify(self, evt)
if isinstance(evt, ReadLogContinueEvent) and evt.getSource() == self:
log.debug("Continuing read of file")
# Continue to read the log
try:
self._progress += log_parser.read_log(
self._logfile_hndl, self._db, LINEINCR)
log.debug("Read %d %% of file (%d / %d)" % (self.getProgress(),
self._progress,
self._log_size))
except log_parser.EndOfLogException, e:
self._progress = self._log_size
# Log file is complete, updated the db entry
self._mark_complete()
# Add an event to notify that the file is complete
self._logfile_hndl.close()
new_evt = ReadLogCompleteEvent(self)
self.getAgent().addEvent(new_evt)
except log_parser.InvalidLogException, e:
log.warning("Invalid log file: %s" % str(e))
self._logfile_hndl.close()
new_evt = ReadLogCompleteEvent(self)
self.getAgent().addEvent(new_evt)
else:
# Add an event to continue reading
new_evt = ReadLogContinueEvent(self)
self.getAgent().addEvent(new_evt)
def _update_db(self):
"""Update the entry in the database for this logfile"""
log.debug("Updating file %s" % self._logfile_path)
pass
def _mark_invalid(self):
"""Update the database to indicate that this is not a valid log file"""
log.debug("Marking file %s invalid" % self._logfile_path)
pass
def _mark_complete(self):
log.debug("Marking file %s complete" % self._logfile_path)
pass
def getProgress(self):
"""Return a percentage complete value"""
if self._log_size == 0:
return 0
return int((float(self._progress) / self._log_size) * 100)
<|fim▁end|> | """Event to indicate we should continue reading the file. Log file
processing will be done in chunks so as not to block the agent for
too long."""
pass |
<|file_name|>read_job.py<|end_file_name|><|fim▁begin|># JoeTraffic - Web-Log Analysis Application utilizing the JoeAgent Framework.
# Copyright (C) 2004 Rhett Garber
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
from JoeAgent import job, event
import db_interface
import os, os.path
import logging
import log_parser
LINEINCR = 30
log = logging.getLogger("agent.LogReader")
class ReadLogCompleteEvent(event.Event):
"""Event to indicate the file is completely read. This event will
be caught by the FindLogJob that is watching it. The file will
continue to be checked for modifications"""
pass
class ReadLogContinueEvent(event.Event):
"""Event to indicate we should continue reading the file. Log file
processing will be done in chunks so as not to block the agent for
too long."""
pass
class ReadLogJob(job.Job):
<|fim_middle|>
<|fim▁end|> | def __init__(self, agent_obj, logfile):
job.Job.__init__(self, agent_obj)
assert os.path.isfile(logfile), "Not a file: %s" % str(logfile)
self._log_size = os.stat(logfile).st_size
log.debug("Log size is %d" % self._log_size)
self._logfile_path = logfile
self._logfile_hndl = open(logfile, 'r')
self._progress = 0 # Data read from file
self._db = db_interface.getDB()
def getFilePath(self):
return self._logfile_path
def getBytesRead(self):
return self._progress
def getBytesTotal(self):
return self._log_size
def run(self):
evt = ReadLogContinueEvent(self)
self.getAgent().addEvent(evt)
def notify(self, evt):
job.Job.notify(self, evt)
if isinstance(evt, ReadLogContinueEvent) and evt.getSource() == self:
log.debug("Continuing read of file")
# Continue to read the log
try:
self._progress += log_parser.read_log(
self._logfile_hndl, self._db, LINEINCR)
log.debug("Read %d %% of file (%d / %d)" % (self.getProgress(),
self._progress,
self._log_size))
except log_parser.EndOfLogException, e:
self._progress = self._log_size
# Log file is complete, updated the db entry
self._mark_complete()
# Add an event to notify that the file is complete
self._logfile_hndl.close()
new_evt = ReadLogCompleteEvent(self)
self.getAgent().addEvent(new_evt)
except log_parser.InvalidLogException, e:
log.warning("Invalid log file: %s" % str(e))
self._logfile_hndl.close()
new_evt = ReadLogCompleteEvent(self)
self.getAgent().addEvent(new_evt)
else:
# Add an event to continue reading
new_evt = ReadLogContinueEvent(self)
self.getAgent().addEvent(new_evt)
def _update_db(self):
"""Update the entry in the database for this logfile"""
log.debug("Updating file %s" % self._logfile_path)
pass
def _mark_invalid(self):
"""Update the database to indicate that this is not a valid log file"""
log.debug("Marking file %s invalid" % self._logfile_path)
pass
def _mark_complete(self):
log.debug("Marking file %s complete" % self._logfile_path)
pass
def getProgress(self):
"""Return a percentage complete value"""
if self._log_size == 0:
return 0
return int((float(self._progress) / self._log_size) * 100) |
<|file_name|>read_job.py<|end_file_name|><|fim▁begin|># JoeTraffic - Web-Log Analysis Application utilizing the JoeAgent Framework.
# Copyright (C) 2004 Rhett Garber
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
from JoeAgent import job, event
import db_interface
import os, os.path
import logging
import log_parser
LINEINCR = 30
log = logging.getLogger("agent.LogReader")
class ReadLogCompleteEvent(event.Event):
"""Event to indicate the file is completely read. This event will
be caught by the FindLogJob that is watching it. The file will
continue to be checked for modifications"""
pass
class ReadLogContinueEvent(event.Event):
"""Event to indicate we should continue reading the file. Log file
processing will be done in chunks so as not to block the agent for
too long."""
pass
class ReadLogJob(job.Job):
def __init__(self, agent_obj, logfile):
<|fim_middle|>
def getFilePath(self):
return self._logfile_path
def getBytesRead(self):
return self._progress
def getBytesTotal(self):
return self._log_size
def run(self):
evt = ReadLogContinueEvent(self)
self.getAgent().addEvent(evt)
def notify(self, evt):
job.Job.notify(self, evt)
if isinstance(evt, ReadLogContinueEvent) and evt.getSource() == self:
log.debug("Continuing read of file")
# Continue to read the log
try:
self._progress += log_parser.read_log(
self._logfile_hndl, self._db, LINEINCR)
log.debug("Read %d %% of file (%d / %d)" % (self.getProgress(),
self._progress,
self._log_size))
except log_parser.EndOfLogException, e:
self._progress = self._log_size
# Log file is complete, updated the db entry
self._mark_complete()
# Add an event to notify that the file is complete
self._logfile_hndl.close()
new_evt = ReadLogCompleteEvent(self)
self.getAgent().addEvent(new_evt)
except log_parser.InvalidLogException, e:
log.warning("Invalid log file: %s" % str(e))
self._logfile_hndl.close()
new_evt = ReadLogCompleteEvent(self)
self.getAgent().addEvent(new_evt)
else:
# Add an event to continue reading
new_evt = ReadLogContinueEvent(self)
self.getAgent().addEvent(new_evt)
def _update_db(self):
"""Update the entry in the database for this logfile"""
log.debug("Updating file %s" % self._logfile_path)
pass
def _mark_invalid(self):
"""Update the database to indicate that this is not a valid log file"""
log.debug("Marking file %s invalid" % self._logfile_path)
pass
def _mark_complete(self):
log.debug("Marking file %s complete" % self._logfile_path)
pass
def getProgress(self):
"""Return a percentage complete value"""
if self._log_size == 0:
return 0
return int((float(self._progress) / self._log_size) * 100)
<|fim▁end|> | job.Job.__init__(self, agent_obj)
assert os.path.isfile(logfile), "Not a file: %s" % str(logfile)
self._log_size = os.stat(logfile).st_size
log.debug("Log size is %d" % self._log_size)
self._logfile_path = logfile
self._logfile_hndl = open(logfile, 'r')
self._progress = 0 # Data read from file
self._db = db_interface.getDB() |
<|file_name|>read_job.py<|end_file_name|><|fim▁begin|># JoeTraffic - Web-Log Analysis Application utilizing the JoeAgent Framework.
# Copyright (C) 2004 Rhett Garber
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
from JoeAgent import job, event
import db_interface
import os, os.path
import logging
import log_parser
LINEINCR = 30
log = logging.getLogger("agent.LogReader")
class ReadLogCompleteEvent(event.Event):
"""Event to indicate the file is completely read. This event will
be caught by the FindLogJob that is watching it. The file will
continue to be checked for modifications"""
pass
class ReadLogContinueEvent(event.Event):
"""Event to indicate we should continue reading the file. Log file
processing will be done in chunks so as not to block the agent for
too long."""
pass
class ReadLogJob(job.Job):
def __init__(self, agent_obj, logfile):
job.Job.__init__(self, agent_obj)
assert os.path.isfile(logfile), "Not a file: %s" % str(logfile)
self._log_size = os.stat(logfile).st_size
log.debug("Log size is %d" % self._log_size)
self._logfile_path = logfile
self._logfile_hndl = open(logfile, 'r')
self._progress = 0 # Data read from file
self._db = db_interface.getDB()
def getFilePath(self):
<|fim_middle|>
def getBytesRead(self):
return self._progress
def getBytesTotal(self):
return self._log_size
def run(self):
evt = ReadLogContinueEvent(self)
self.getAgent().addEvent(evt)
def notify(self, evt):
job.Job.notify(self, evt)
if isinstance(evt, ReadLogContinueEvent) and evt.getSource() == self:
log.debug("Continuing read of file")
# Continue to read the log
try:
self._progress += log_parser.read_log(
self._logfile_hndl, self._db, LINEINCR)
log.debug("Read %d %% of file (%d / %d)" % (self.getProgress(),
self._progress,
self._log_size))
except log_parser.EndOfLogException, e:
self._progress = self._log_size
# Log file is complete, updated the db entry
self._mark_complete()
# Add an event to notify that the file is complete
self._logfile_hndl.close()
new_evt = ReadLogCompleteEvent(self)
self.getAgent().addEvent(new_evt)
except log_parser.InvalidLogException, e:
log.warning("Invalid log file: %s" % str(e))
self._logfile_hndl.close()
new_evt = ReadLogCompleteEvent(self)
self.getAgent().addEvent(new_evt)
else:
# Add an event to continue reading
new_evt = ReadLogContinueEvent(self)
self.getAgent().addEvent(new_evt)
def _update_db(self):
"""Update the entry in the database for this logfile"""
log.debug("Updating file %s" % self._logfile_path)
pass
def _mark_invalid(self):
"""Update the database to indicate that this is not a valid log file"""
log.debug("Marking file %s invalid" % self._logfile_path)
pass
def _mark_complete(self):
log.debug("Marking file %s complete" % self._logfile_path)
pass
def getProgress(self):
"""Return a percentage complete value"""
if self._log_size == 0:
return 0
return int((float(self._progress) / self._log_size) * 100)
<|fim▁end|> | return self._logfile_path |
<|file_name|>read_job.py<|end_file_name|><|fim▁begin|># JoeTraffic - Web-Log Analysis Application utilizing the JoeAgent Framework.
# Copyright (C) 2004 Rhett Garber
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
from JoeAgent import job, event
import db_interface
import os, os.path
import logging
import log_parser
LINEINCR = 30
log = logging.getLogger("agent.LogReader")
class ReadLogCompleteEvent(event.Event):
"""Event to indicate the file is completely read. This event will
be caught by the FindLogJob that is watching it. The file will
continue to be checked for modifications"""
pass
class ReadLogContinueEvent(event.Event):
"""Event to indicate we should continue reading the file. Log file
processing will be done in chunks so as not to block the agent for
too long."""
pass
class ReadLogJob(job.Job):
def __init__(self, agent_obj, logfile):
job.Job.__init__(self, agent_obj)
assert os.path.isfile(logfile), "Not a file: %s" % str(logfile)
self._log_size = os.stat(logfile).st_size
log.debug("Log size is %d" % self._log_size)
self._logfile_path = logfile
self._logfile_hndl = open(logfile, 'r')
self._progress = 0 # Data read from file
self._db = db_interface.getDB()
def getFilePath(self):
return self._logfile_path
def getBytesRead(self):
<|fim_middle|>
def getBytesTotal(self):
return self._log_size
def run(self):
evt = ReadLogContinueEvent(self)
self.getAgent().addEvent(evt)
def notify(self, evt):
job.Job.notify(self, evt)
if isinstance(evt, ReadLogContinueEvent) and evt.getSource() == self:
log.debug("Continuing read of file")
# Continue to read the log
try:
self._progress += log_parser.read_log(
self._logfile_hndl, self._db, LINEINCR)
log.debug("Read %d %% of file (%d / %d)" % (self.getProgress(),
self._progress,
self._log_size))
except log_parser.EndOfLogException, e:
self._progress = self._log_size
# Log file is complete, updated the db entry
self._mark_complete()
# Add an event to notify that the file is complete
self._logfile_hndl.close()
new_evt = ReadLogCompleteEvent(self)
self.getAgent().addEvent(new_evt)
except log_parser.InvalidLogException, e:
log.warning("Invalid log file: %s" % str(e))
self._logfile_hndl.close()
new_evt = ReadLogCompleteEvent(self)
self.getAgent().addEvent(new_evt)
else:
# Add an event to continue reading
new_evt = ReadLogContinueEvent(self)
self.getAgent().addEvent(new_evt)
def _update_db(self):
"""Update the entry in the database for this logfile"""
log.debug("Updating file %s" % self._logfile_path)
pass
def _mark_invalid(self):
"""Update the database to indicate that this is not a valid log file"""
log.debug("Marking file %s invalid" % self._logfile_path)
pass
def _mark_complete(self):
log.debug("Marking file %s complete" % self._logfile_path)
pass
def getProgress(self):
"""Return a percentage complete value"""
if self._log_size == 0:
return 0
return int((float(self._progress) / self._log_size) * 100)
<|fim▁end|> | return self._progress |
<|file_name|>read_job.py<|end_file_name|><|fim▁begin|># JoeTraffic - Web-Log Analysis Application utilizing the JoeAgent Framework.
# Copyright (C) 2004 Rhett Garber
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
from JoeAgent import job, event
import db_interface
import os, os.path
import logging
import log_parser
LINEINCR = 30
log = logging.getLogger("agent.LogReader")
class ReadLogCompleteEvent(event.Event):
"""Event to indicate the file is completely read. This event will
be caught by the FindLogJob that is watching it. The file will
continue to be checked for modifications"""
pass
class ReadLogContinueEvent(event.Event):
"""Event to indicate we should continue reading the file. Log file
processing will be done in chunks so as not to block the agent for
too long."""
pass
class ReadLogJob(job.Job):
def __init__(self, agent_obj, logfile):
job.Job.__init__(self, agent_obj)
assert os.path.isfile(logfile), "Not a file: %s" % str(logfile)
self._log_size = os.stat(logfile).st_size
log.debug("Log size is %d" % self._log_size)
self._logfile_path = logfile
self._logfile_hndl = open(logfile, 'r')
self._progress = 0 # Data read from file
self._db = db_interface.getDB()
def getFilePath(self):
return self._logfile_path
def getBytesRead(self):
return self._progress
def getBytesTotal(self):
<|fim_middle|>
def run(self):
evt = ReadLogContinueEvent(self)
self.getAgent().addEvent(evt)
def notify(self, evt):
job.Job.notify(self, evt)
if isinstance(evt, ReadLogContinueEvent) and evt.getSource() == self:
log.debug("Continuing read of file")
# Continue to read the log
try:
self._progress += log_parser.read_log(
self._logfile_hndl, self._db, LINEINCR)
log.debug("Read %d %% of file (%d / %d)" % (self.getProgress(),
self._progress,
self._log_size))
except log_parser.EndOfLogException, e:
self._progress = self._log_size
# Log file is complete, updated the db entry
self._mark_complete()
# Add an event to notify that the file is complete
self._logfile_hndl.close()
new_evt = ReadLogCompleteEvent(self)
self.getAgent().addEvent(new_evt)
except log_parser.InvalidLogException, e:
log.warning("Invalid log file: %s" % str(e))
self._logfile_hndl.close()
new_evt = ReadLogCompleteEvent(self)
self.getAgent().addEvent(new_evt)
else:
# Add an event to continue reading
new_evt = ReadLogContinueEvent(self)
self.getAgent().addEvent(new_evt)
def _update_db(self):
"""Update the entry in the database for this logfile"""
log.debug("Updating file %s" % self._logfile_path)
pass
def _mark_invalid(self):
"""Update the database to indicate that this is not a valid log file"""
log.debug("Marking file %s invalid" % self._logfile_path)
pass
def _mark_complete(self):
log.debug("Marking file %s complete" % self._logfile_path)
pass
def getProgress(self):
"""Return a percentage complete value"""
if self._log_size == 0:
return 0
return int((float(self._progress) / self._log_size) * 100)
<|fim▁end|> | return self._log_size |
<|file_name|>read_job.py<|end_file_name|><|fim▁begin|># JoeTraffic - Web-Log Analysis Application utilizing the JoeAgent Framework.
# Copyright (C) 2004 Rhett Garber
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
from JoeAgent import job, event
import db_interface
import os, os.path
import logging
import log_parser
LINEINCR = 30
log = logging.getLogger("agent.LogReader")
class ReadLogCompleteEvent(event.Event):
"""Event to indicate the file is completely read. This event will
be caught by the FindLogJob that is watching it. The file will
continue to be checked for modifications"""
pass
class ReadLogContinueEvent(event.Event):
"""Event to indicate we should continue reading the file. Log file
processing will be done in chunks so as not to block the agent for
too long."""
pass
class ReadLogJob(job.Job):
def __init__(self, agent_obj, logfile):
job.Job.__init__(self, agent_obj)
assert os.path.isfile(logfile), "Not a file: %s" % str(logfile)
self._log_size = os.stat(logfile).st_size
log.debug("Log size is %d" % self._log_size)
self._logfile_path = logfile
self._logfile_hndl = open(logfile, 'r')
self._progress = 0 # Data read from file
self._db = db_interface.getDB()
def getFilePath(self):
return self._logfile_path
def getBytesRead(self):
return self._progress
def getBytesTotal(self):
return self._log_size
def run(self):
<|fim_middle|>
def notify(self, evt):
job.Job.notify(self, evt)
if isinstance(evt, ReadLogContinueEvent) and evt.getSource() == self:
log.debug("Continuing read of file")
# Continue to read the log
try:
self._progress += log_parser.read_log(
self._logfile_hndl, self._db, LINEINCR)
log.debug("Read %d %% of file (%d / %d)" % (self.getProgress(),
self._progress,
self._log_size))
except log_parser.EndOfLogException, e:
self._progress = self._log_size
# Log file is complete, updated the db entry
self._mark_complete()
# Add an event to notify that the file is complete
self._logfile_hndl.close()
new_evt = ReadLogCompleteEvent(self)
self.getAgent().addEvent(new_evt)
except log_parser.InvalidLogException, e:
log.warning("Invalid log file: %s" % str(e))
self._logfile_hndl.close()
new_evt = ReadLogCompleteEvent(self)
self.getAgent().addEvent(new_evt)
else:
# Add an event to continue reading
new_evt = ReadLogContinueEvent(self)
self.getAgent().addEvent(new_evt)
def _update_db(self):
"""Update the entry in the database for this logfile"""
log.debug("Updating file %s" % self._logfile_path)
pass
def _mark_invalid(self):
"""Update the database to indicate that this is not a valid log file"""
log.debug("Marking file %s invalid" % self._logfile_path)
pass
def _mark_complete(self):
log.debug("Marking file %s complete" % self._logfile_path)
pass
def getProgress(self):
"""Return a percentage complete value"""
if self._log_size == 0:
return 0
return int((float(self._progress) / self._log_size) * 100)
<|fim▁end|> | evt = ReadLogContinueEvent(self)
self.getAgent().addEvent(evt) |
<|file_name|>read_job.py<|end_file_name|><|fim▁begin|># JoeTraffic - Web-Log Analysis Application utilizing the JoeAgent Framework.
# Copyright (C) 2004 Rhett Garber
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
from JoeAgent import job, event
import db_interface
import os, os.path
import logging
import log_parser
LINEINCR = 30
log = logging.getLogger("agent.LogReader")
class ReadLogCompleteEvent(event.Event):
"""Event to indicate the file is completely read. This event will
be caught by the FindLogJob that is watching it. The file will
continue to be checked for modifications"""
pass
class ReadLogContinueEvent(event.Event):
"""Event to indicate we should continue reading the file. Log file
processing will be done in chunks so as not to block the agent for
too long."""
pass
class ReadLogJob(job.Job):
def __init__(self, agent_obj, logfile):
job.Job.__init__(self, agent_obj)
assert os.path.isfile(logfile), "Not a file: %s" % str(logfile)
self._log_size = os.stat(logfile).st_size
log.debug("Log size is %d" % self._log_size)
self._logfile_path = logfile
self._logfile_hndl = open(logfile, 'r')
self._progress = 0 # Data read from file
self._db = db_interface.getDB()
def getFilePath(self):
return self._logfile_path
def getBytesRead(self):
return self._progress
def getBytesTotal(self):
return self._log_size
def run(self):
evt = ReadLogContinueEvent(self)
self.getAgent().addEvent(evt)
def notify(self, evt):
<|fim_middle|>
def _update_db(self):
"""Update the entry in the database for this logfile"""
log.debug("Updating file %s" % self._logfile_path)
pass
def _mark_invalid(self):
"""Update the database to indicate that this is not a valid log file"""
log.debug("Marking file %s invalid" % self._logfile_path)
pass
def _mark_complete(self):
log.debug("Marking file %s complete" % self._logfile_path)
pass
def getProgress(self):
"""Return a percentage complete value"""
if self._log_size == 0:
return 0
return int((float(self._progress) / self._log_size) * 100)
<|fim▁end|> | job.Job.notify(self, evt)
if isinstance(evt, ReadLogContinueEvent) and evt.getSource() == self:
log.debug("Continuing read of file")
# Continue to read the log
try:
self._progress += log_parser.read_log(
self._logfile_hndl, self._db, LINEINCR)
log.debug("Read %d %% of file (%d / %d)" % (self.getProgress(),
self._progress,
self._log_size))
except log_parser.EndOfLogException, e:
self._progress = self._log_size
# Log file is complete, updated the db entry
self._mark_complete()
# Add an event to notify that the file is complete
self._logfile_hndl.close()
new_evt = ReadLogCompleteEvent(self)
self.getAgent().addEvent(new_evt)
except log_parser.InvalidLogException, e:
log.warning("Invalid log file: %s" % str(e))
self._logfile_hndl.close()
new_evt = ReadLogCompleteEvent(self)
self.getAgent().addEvent(new_evt)
else:
# Add an event to continue reading
new_evt = ReadLogContinueEvent(self)
self.getAgent().addEvent(new_evt) |
<|file_name|>read_job.py<|end_file_name|><|fim▁begin|># JoeTraffic - Web-Log Analysis Application utilizing the JoeAgent Framework.
# Copyright (C) 2004 Rhett Garber
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
from JoeAgent import job, event
import db_interface
import os, os.path
import logging
import log_parser
LINEINCR = 30
log = logging.getLogger("agent.LogReader")
class ReadLogCompleteEvent(event.Event):
"""Event to indicate the file is completely read. This event will
be caught by the FindLogJob that is watching it. The file will
continue to be checked for modifications"""
pass
class ReadLogContinueEvent(event.Event):
"""Event to indicate we should continue reading the file. Log file
processing will be done in chunks so as not to block the agent for
too long."""
pass
class ReadLogJob(job.Job):
def __init__(self, agent_obj, logfile):
job.Job.__init__(self, agent_obj)
assert os.path.isfile(logfile), "Not a file: %s" % str(logfile)
self._log_size = os.stat(logfile).st_size
log.debug("Log size is %d" % self._log_size)
self._logfile_path = logfile
self._logfile_hndl = open(logfile, 'r')
self._progress = 0 # Data read from file
self._db = db_interface.getDB()
def getFilePath(self):
return self._logfile_path
def getBytesRead(self):
return self._progress
def getBytesTotal(self):
return self._log_size
def run(self):
evt = ReadLogContinueEvent(self)
self.getAgent().addEvent(evt)
def notify(self, evt):
job.Job.notify(self, evt)
if isinstance(evt, ReadLogContinueEvent) and evt.getSource() == self:
log.debug("Continuing read of file")
# Continue to read the log
try:
self._progress += log_parser.read_log(
self._logfile_hndl, self._db, LINEINCR)
log.debug("Read %d %% of file (%d / %d)" % (self.getProgress(),
self._progress,
self._log_size))
except log_parser.EndOfLogException, e:
self._progress = self._log_size
# Log file is complete, updated the db entry
self._mark_complete()
# Add an event to notify that the file is complete
self._logfile_hndl.close()
new_evt = ReadLogCompleteEvent(self)
self.getAgent().addEvent(new_evt)
except log_parser.InvalidLogException, e:
log.warning("Invalid log file: %s" % str(e))
self._logfile_hndl.close()
new_evt = ReadLogCompleteEvent(self)
self.getAgent().addEvent(new_evt)
else:
# Add an event to continue reading
new_evt = ReadLogContinueEvent(self)
self.getAgent().addEvent(new_evt)
def _update_db(self):
<|fim_middle|>
def _mark_invalid(self):
"""Update the database to indicate that this is not a valid log file"""
log.debug("Marking file %s invalid" % self._logfile_path)
pass
def _mark_complete(self):
log.debug("Marking file %s complete" % self._logfile_path)
pass
def getProgress(self):
"""Return a percentage complete value"""
if self._log_size == 0:
return 0
return int((float(self._progress) / self._log_size) * 100)
<|fim▁end|> | """Update the entry in the database for this logfile"""
log.debug("Updating file %s" % self._logfile_path)
pass |
<|file_name|>read_job.py<|end_file_name|><|fim▁begin|># JoeTraffic - Web-Log Analysis Application utilizing the JoeAgent Framework.
# Copyright (C) 2004 Rhett Garber
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
from JoeAgent import job, event
import db_interface
import os, os.path
import logging
import log_parser
LINEINCR = 30
log = logging.getLogger("agent.LogReader")
class ReadLogCompleteEvent(event.Event):
"""Event to indicate the file is completely read. This event will
be caught by the FindLogJob that is watching it. The file will
continue to be checked for modifications"""
pass
class ReadLogContinueEvent(event.Event):
"""Event to indicate we should continue reading the file. Log file
processing will be done in chunks so as not to block the agent for
too long."""
pass
class ReadLogJob(job.Job):
def __init__(self, agent_obj, logfile):
job.Job.__init__(self, agent_obj)
assert os.path.isfile(logfile), "Not a file: %s" % str(logfile)
self._log_size = os.stat(logfile).st_size
log.debug("Log size is %d" % self._log_size)
self._logfile_path = logfile
self._logfile_hndl = open(logfile, 'r')
self._progress = 0 # Data read from file
self._db = db_interface.getDB()
def getFilePath(self):
return self._logfile_path
def getBytesRead(self):
return self._progress
def getBytesTotal(self):
return self._log_size
def run(self):
evt = ReadLogContinueEvent(self)
self.getAgent().addEvent(evt)
def notify(self, evt):
job.Job.notify(self, evt)
if isinstance(evt, ReadLogContinueEvent) and evt.getSource() == self:
log.debug("Continuing read of file")
# Continue to read the log
try:
self._progress += log_parser.read_log(
self._logfile_hndl, self._db, LINEINCR)
log.debug("Read %d %% of file (%d / %d)" % (self.getProgress(),
self._progress,
self._log_size))
except log_parser.EndOfLogException, e:
self._progress = self._log_size
# Log file is complete, updated the db entry
self._mark_complete()
# Add an event to notify that the file is complete
self._logfile_hndl.close()
new_evt = ReadLogCompleteEvent(self)
self.getAgent().addEvent(new_evt)
except log_parser.InvalidLogException, e:
log.warning("Invalid log file: %s" % str(e))
self._logfile_hndl.close()
new_evt = ReadLogCompleteEvent(self)
self.getAgent().addEvent(new_evt)
else:
# Add an event to continue reading
new_evt = ReadLogContinueEvent(self)
self.getAgent().addEvent(new_evt)
def _update_db(self):
"""Update the entry in the database for this logfile"""
log.debug("Updating file %s" % self._logfile_path)
pass
def _mark_invalid(self):
<|fim_middle|>
def _mark_complete(self):
log.debug("Marking file %s complete" % self._logfile_path)
pass
def getProgress(self):
"""Return a percentage complete value"""
if self._log_size == 0:
return 0
return int((float(self._progress) / self._log_size) * 100)
<|fim▁end|> | """Update the database to indicate that this is not a valid log file"""
log.debug("Marking file %s invalid" % self._logfile_path)
pass |
<|file_name|>read_job.py<|end_file_name|><|fim▁begin|># JoeTraffic - Web-Log Analysis Application utilizing the JoeAgent Framework.
# Copyright (C) 2004 Rhett Garber
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
from JoeAgent import job, event
import db_interface
import os, os.path
import logging
import log_parser
LINEINCR = 30
log = logging.getLogger("agent.LogReader")
class ReadLogCompleteEvent(event.Event):
"""Event to indicate the file is completely read. This event will
be caught by the FindLogJob that is watching it. The file will
continue to be checked for modifications"""
pass
class ReadLogContinueEvent(event.Event):
"""Event to indicate we should continue reading the file. Log file
processing will be done in chunks so as not to block the agent for
too long."""
pass
class ReadLogJob(job.Job):
def __init__(self, agent_obj, logfile):
job.Job.__init__(self, agent_obj)
assert os.path.isfile(logfile), "Not a file: %s" % str(logfile)
self._log_size = os.stat(logfile).st_size
log.debug("Log size is %d" % self._log_size)
self._logfile_path = logfile
self._logfile_hndl = open(logfile, 'r')
self._progress = 0 # Data read from file
self._db = db_interface.getDB()
def getFilePath(self):
return self._logfile_path
def getBytesRead(self):
return self._progress
def getBytesTotal(self):
return self._log_size
def run(self):
evt = ReadLogContinueEvent(self)
self.getAgent().addEvent(evt)
def notify(self, evt):
job.Job.notify(self, evt)
if isinstance(evt, ReadLogContinueEvent) and evt.getSource() == self:
log.debug("Continuing read of file")
# Continue to read the log
try:
self._progress += log_parser.read_log(
self._logfile_hndl, self._db, LINEINCR)
log.debug("Read %d %% of file (%d / %d)" % (self.getProgress(),
self._progress,
self._log_size))
except log_parser.EndOfLogException, e:
self._progress = self._log_size
# Log file is complete, updated the db entry
self._mark_complete()
# Add an event to notify that the file is complete
self._logfile_hndl.close()
new_evt = ReadLogCompleteEvent(self)
self.getAgent().addEvent(new_evt)
except log_parser.InvalidLogException, e:
log.warning("Invalid log file: %s" % str(e))
self._logfile_hndl.close()
new_evt = ReadLogCompleteEvent(self)
self.getAgent().addEvent(new_evt)
else:
# Add an event to continue reading
new_evt = ReadLogContinueEvent(self)
self.getAgent().addEvent(new_evt)
def _update_db(self):
"""Update the entry in the database for this logfile"""
log.debug("Updating file %s" % self._logfile_path)
pass
def _mark_invalid(self):
"""Update the database to indicate that this is not a valid log file"""
log.debug("Marking file %s invalid" % self._logfile_path)
pass
def _mark_complete(self):
<|fim_middle|>
def getProgress(self):
"""Return a percentage complete value"""
if self._log_size == 0:
return 0
return int((float(self._progress) / self._log_size) * 100)
<|fim▁end|> | log.debug("Marking file %s complete" % self._logfile_path)
pass |
<|file_name|>read_job.py<|end_file_name|><|fim▁begin|># JoeTraffic - Web-Log Analysis Application utilizing the JoeAgent Framework.
# Copyright (C) 2004 Rhett Garber
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
from JoeAgent import job, event
import db_interface
import os, os.path
import logging
import log_parser
LINEINCR = 30
log = logging.getLogger("agent.LogReader")
class ReadLogCompleteEvent(event.Event):
"""Event to indicate the file is completely read. This event will
be caught by the FindLogJob that is watching it. The file will
continue to be checked for modifications"""
pass
class ReadLogContinueEvent(event.Event):
"""Event to indicate we should continue reading the file. Log file
processing will be done in chunks so as not to block the agent for
too long."""
pass
class ReadLogJob(job.Job):
def __init__(self, agent_obj, logfile):
job.Job.__init__(self, agent_obj)
assert os.path.isfile(logfile), "Not a file: %s" % str(logfile)
self._log_size = os.stat(logfile).st_size
log.debug("Log size is %d" % self._log_size)
self._logfile_path = logfile
self._logfile_hndl = open(logfile, 'r')
self._progress = 0 # Data read from file
self._db = db_interface.getDB()
def getFilePath(self):
return self._logfile_path
def getBytesRead(self):
return self._progress
def getBytesTotal(self):
return self._log_size
def run(self):
evt = ReadLogContinueEvent(self)
self.getAgent().addEvent(evt)
def notify(self, evt):
job.Job.notify(self, evt)
if isinstance(evt, ReadLogContinueEvent) and evt.getSource() == self:
log.debug("Continuing read of file")
# Continue to read the log
try:
self._progress += log_parser.read_log(
self._logfile_hndl, self._db, LINEINCR)
log.debug("Read %d %% of file (%d / %d)" % (self.getProgress(),
self._progress,
self._log_size))
except log_parser.EndOfLogException, e:
self._progress = self._log_size
# Log file is complete, updated the db entry
self._mark_complete()
# Add an event to notify that the file is complete
self._logfile_hndl.close()
new_evt = ReadLogCompleteEvent(self)
self.getAgent().addEvent(new_evt)
except log_parser.InvalidLogException, e:
log.warning("Invalid log file: %s" % str(e))
self._logfile_hndl.close()
new_evt = ReadLogCompleteEvent(self)
self.getAgent().addEvent(new_evt)
else:
# Add an event to continue reading
new_evt = ReadLogContinueEvent(self)
self.getAgent().addEvent(new_evt)
def _update_db(self):
"""Update the entry in the database for this logfile"""
log.debug("Updating file %s" % self._logfile_path)
pass
def _mark_invalid(self):
"""Update the database to indicate that this is not a valid log file"""
log.debug("Marking file %s invalid" % self._logfile_path)
pass
def _mark_complete(self):
log.debug("Marking file %s complete" % self._logfile_path)
pass
def getProgress(self):
<|fim_middle|>
<|fim▁end|> | """Return a percentage complete value"""
if self._log_size == 0:
return 0
return int((float(self._progress) / self._log_size) * 100) |
<|file_name|>read_job.py<|end_file_name|><|fim▁begin|># JoeTraffic - Web-Log Analysis Application utilizing the JoeAgent Framework.
# Copyright (C) 2004 Rhett Garber
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
from JoeAgent import job, event
import db_interface
import os, os.path
import logging
import log_parser
LINEINCR = 30
log = logging.getLogger("agent.LogReader")
class ReadLogCompleteEvent(event.Event):
"""Event to indicate the file is completely read. This event will
be caught by the FindLogJob that is watching it. The file will
continue to be checked for modifications"""
pass
class ReadLogContinueEvent(event.Event):
"""Event to indicate we should continue reading the file. Log file
processing will be done in chunks so as not to block the agent for
too long."""
pass
class ReadLogJob(job.Job):
def __init__(self, agent_obj, logfile):
job.Job.__init__(self, agent_obj)
assert os.path.isfile(logfile), "Not a file: %s" % str(logfile)
self._log_size = os.stat(logfile).st_size
log.debug("Log size is %d" % self._log_size)
self._logfile_path = logfile
self._logfile_hndl = open(logfile, 'r')
self._progress = 0 # Data read from file
self._db = db_interface.getDB()
def getFilePath(self):
return self._logfile_path
def getBytesRead(self):
return self._progress
def getBytesTotal(self):
return self._log_size
def run(self):
evt = ReadLogContinueEvent(self)
self.getAgent().addEvent(evt)
def notify(self, evt):
job.Job.notify(self, evt)
if isinstance(evt, ReadLogContinueEvent) and evt.getSource() == self:
<|fim_middle|>
def _update_db(self):
"""Update the entry in the database for this logfile"""
log.debug("Updating file %s" % self._logfile_path)
pass
def _mark_invalid(self):
"""Update the database to indicate that this is not a valid log file"""
log.debug("Marking file %s invalid" % self._logfile_path)
pass
def _mark_complete(self):
log.debug("Marking file %s complete" % self._logfile_path)
pass
def getProgress(self):
"""Return a percentage complete value"""
if self._log_size == 0:
return 0
return int((float(self._progress) / self._log_size) * 100)
<|fim▁end|> | log.debug("Continuing read of file")
# Continue to read the log
try:
self._progress += log_parser.read_log(
self._logfile_hndl, self._db, LINEINCR)
log.debug("Read %d %% of file (%d / %d)" % (self.getProgress(),
self._progress,
self._log_size))
except log_parser.EndOfLogException, e:
self._progress = self._log_size
# Log file is complete, updated the db entry
self._mark_complete()
# Add an event to notify that the file is complete
self._logfile_hndl.close()
new_evt = ReadLogCompleteEvent(self)
self.getAgent().addEvent(new_evt)
except log_parser.InvalidLogException, e:
log.warning("Invalid log file: %s" % str(e))
self._logfile_hndl.close()
new_evt = ReadLogCompleteEvent(self)
self.getAgent().addEvent(new_evt)
else:
# Add an event to continue reading
new_evt = ReadLogContinueEvent(self)
self.getAgent().addEvent(new_evt) |
<|file_name|>read_job.py<|end_file_name|><|fim▁begin|># JoeTraffic - Web-Log Analysis Application utilizing the JoeAgent Framework.
# Copyright (C) 2004 Rhett Garber
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
from JoeAgent import job, event
import db_interface
import os, os.path
import logging
import log_parser
LINEINCR = 30
log = logging.getLogger("agent.LogReader")
class ReadLogCompleteEvent(event.Event):
"""Event to indicate the file is completely read. This event will
be caught by the FindLogJob that is watching it. The file will
continue to be checked for modifications"""
pass
class ReadLogContinueEvent(event.Event):
"""Event to indicate we should continue reading the file. Log file
processing will be done in chunks so as not to block the agent for
too long."""
pass
class ReadLogJob(job.Job):
def __init__(self, agent_obj, logfile):
job.Job.__init__(self, agent_obj)
assert os.path.isfile(logfile), "Not a file: %s" % str(logfile)
self._log_size = os.stat(logfile).st_size
log.debug("Log size is %d" % self._log_size)
self._logfile_path = logfile
self._logfile_hndl = open(logfile, 'r')
self._progress = 0 # Data read from file
self._db = db_interface.getDB()
def getFilePath(self):
return self._logfile_path
def getBytesRead(self):
return self._progress
def getBytesTotal(self):
return self._log_size
def run(self):
evt = ReadLogContinueEvent(self)
self.getAgent().addEvent(evt)
def notify(self, evt):
job.Job.notify(self, evt)
if isinstance(evt, ReadLogContinueEvent) and evt.getSource() == self:
log.debug("Continuing read of file")
# Continue to read the log
try:
self._progress += log_parser.read_log(
self._logfile_hndl, self._db, LINEINCR)
log.debug("Read %d %% of file (%d / %d)" % (self.getProgress(),
self._progress,
self._log_size))
except log_parser.EndOfLogException, e:
self._progress = self._log_size
# Log file is complete, updated the db entry
self._mark_complete()
# Add an event to notify that the file is complete
self._logfile_hndl.close()
new_evt = ReadLogCompleteEvent(self)
self.getAgent().addEvent(new_evt)
except log_parser.InvalidLogException, e:
log.warning("Invalid log file: %s" % str(e))
self._logfile_hndl.close()
new_evt = ReadLogCompleteEvent(self)
self.getAgent().addEvent(new_evt)
else:
# Add an event to continue reading
<|fim_middle|>
def _update_db(self):
"""Update the entry in the database for this logfile"""
log.debug("Updating file %s" % self._logfile_path)
pass
def _mark_invalid(self):
"""Update the database to indicate that this is not a valid log file"""
log.debug("Marking file %s invalid" % self._logfile_path)
pass
def _mark_complete(self):
log.debug("Marking file %s complete" % self._logfile_path)
pass
def getProgress(self):
"""Return a percentage complete value"""
if self._log_size == 0:
return 0
return int((float(self._progress) / self._log_size) * 100)
<|fim▁end|> | new_evt = ReadLogContinueEvent(self)
self.getAgent().addEvent(new_evt) |
<|file_name|>read_job.py<|end_file_name|><|fim▁begin|># JoeTraffic - Web-Log Analysis Application utilizing the JoeAgent Framework.
# Copyright (C) 2004 Rhett Garber
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
from JoeAgent import job, event
import db_interface
import os, os.path
import logging
import log_parser
LINEINCR = 30
log = logging.getLogger("agent.LogReader")
class ReadLogCompleteEvent(event.Event):
"""Event to indicate the file is completely read. This event will
be caught by the FindLogJob that is watching it. The file will
continue to be checked for modifications"""
pass
class ReadLogContinueEvent(event.Event):
"""Event to indicate we should continue reading the file. Log file
processing will be done in chunks so as not to block the agent for
too long."""
pass
class ReadLogJob(job.Job):
def __init__(self, agent_obj, logfile):
job.Job.__init__(self, agent_obj)
assert os.path.isfile(logfile), "Not a file: %s" % str(logfile)
self._log_size = os.stat(logfile).st_size
log.debug("Log size is %d" % self._log_size)
self._logfile_path = logfile
self._logfile_hndl = open(logfile, 'r')
self._progress = 0 # Data read from file
self._db = db_interface.getDB()
def getFilePath(self):
return self._logfile_path
def getBytesRead(self):
return self._progress
def getBytesTotal(self):
return self._log_size
def run(self):
evt = ReadLogContinueEvent(self)
self.getAgent().addEvent(evt)
def notify(self, evt):
job.Job.notify(self, evt)
if isinstance(evt, ReadLogContinueEvent) and evt.getSource() == self:
log.debug("Continuing read of file")
# Continue to read the log
try:
self._progress += log_parser.read_log(
self._logfile_hndl, self._db, LINEINCR)
log.debug("Read %d %% of file (%d / %d)" % (self.getProgress(),
self._progress,
self._log_size))
except log_parser.EndOfLogException, e:
self._progress = self._log_size
# Log file is complete, updated the db entry
self._mark_complete()
# Add an event to notify that the file is complete
self._logfile_hndl.close()
new_evt = ReadLogCompleteEvent(self)
self.getAgent().addEvent(new_evt)
except log_parser.InvalidLogException, e:
log.warning("Invalid log file: %s" % str(e))
self._logfile_hndl.close()
new_evt = ReadLogCompleteEvent(self)
self.getAgent().addEvent(new_evt)
else:
# Add an event to continue reading
new_evt = ReadLogContinueEvent(self)
self.getAgent().addEvent(new_evt)
def _update_db(self):
"""Update the entry in the database for this logfile"""
log.debug("Updating file %s" % self._logfile_path)
pass
def _mark_invalid(self):
"""Update the database to indicate that this is not a valid log file"""
log.debug("Marking file %s invalid" % self._logfile_path)
pass
def _mark_complete(self):
log.debug("Marking file %s complete" % self._logfile_path)
pass
def getProgress(self):
"""Return a percentage complete value"""
if self._log_size == 0:
<|fim_middle|>
return int((float(self._progress) / self._log_size) * 100)
<|fim▁end|> | return 0 |
<|file_name|>read_job.py<|end_file_name|><|fim▁begin|># JoeTraffic - Web-Log Analysis Application utilizing the JoeAgent Framework.
# Copyright (C) 2004 Rhett Garber
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
from JoeAgent import job, event
import db_interface
import os, os.path
import logging
import log_parser
LINEINCR = 30
log = logging.getLogger("agent.LogReader")
class ReadLogCompleteEvent(event.Event):
"""Event to indicate the file is completely read. This event will
be caught by the FindLogJob that is watching it. The file will
continue to be checked for modifications"""
pass
class ReadLogContinueEvent(event.Event):
"""Event to indicate we should continue reading the file. Log file
processing will be done in chunks so as not to block the agent for
too long."""
pass
class ReadLogJob(job.Job):
def <|fim_middle|>(self, agent_obj, logfile):
job.Job.__init__(self, agent_obj)
assert os.path.isfile(logfile), "Not a file: %s" % str(logfile)
self._log_size = os.stat(logfile).st_size
log.debug("Log size is %d" % self._log_size)
self._logfile_path = logfile
self._logfile_hndl = open(logfile, 'r')
self._progress = 0 # Data read from file
self._db = db_interface.getDB()
def getFilePath(self):
return self._logfile_path
def getBytesRead(self):
return self._progress
def getBytesTotal(self):
return self._log_size
def run(self):
evt = ReadLogContinueEvent(self)
self.getAgent().addEvent(evt)
def notify(self, evt):
job.Job.notify(self, evt)
if isinstance(evt, ReadLogContinueEvent) and evt.getSource() == self:
log.debug("Continuing read of file")
# Continue to read the log
try:
self._progress += log_parser.read_log(
self._logfile_hndl, self._db, LINEINCR)
log.debug("Read %d %% of file (%d / %d)" % (self.getProgress(),
self._progress,
self._log_size))
except log_parser.EndOfLogException, e:
self._progress = self._log_size
# Log file is complete, updated the db entry
self._mark_complete()
# Add an event to notify that the file is complete
self._logfile_hndl.close()
new_evt = ReadLogCompleteEvent(self)
self.getAgent().addEvent(new_evt)
except log_parser.InvalidLogException, e:
log.warning("Invalid log file: %s" % str(e))
self._logfile_hndl.close()
new_evt = ReadLogCompleteEvent(self)
self.getAgent().addEvent(new_evt)
else:
# Add an event to continue reading
new_evt = ReadLogContinueEvent(self)
self.getAgent().addEvent(new_evt)
def _update_db(self):
"""Update the entry in the database for this logfile"""
log.debug("Updating file %s" % self._logfile_path)
pass
def _mark_invalid(self):
"""Update the database to indicate that this is not a valid log file"""
log.debug("Marking file %s invalid" % self._logfile_path)
pass
def _mark_complete(self):
log.debug("Marking file %s complete" % self._logfile_path)
pass
def getProgress(self):
"""Return a percentage complete value"""
if self._log_size == 0:
return 0
return int((float(self._progress) / self._log_size) * 100)
<|fim▁end|> | __init__ |
<|file_name|>read_job.py<|end_file_name|><|fim▁begin|># JoeTraffic - Web-Log Analysis Application utilizing the JoeAgent Framework.
# Copyright (C) 2004 Rhett Garber
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
from JoeAgent import job, event
import db_interface
import os, os.path
import logging
import log_parser
LINEINCR = 30
log = logging.getLogger("agent.LogReader")
class ReadLogCompleteEvent(event.Event):
"""Event to indicate the file is completely read. This event will
be caught by the FindLogJob that is watching it. The file will
continue to be checked for modifications"""
pass
class ReadLogContinueEvent(event.Event):
"""Event to indicate we should continue reading the file. Log file
processing will be done in chunks so as not to block the agent for
too long."""
pass
class ReadLogJob(job.Job):
def __init__(self, agent_obj, logfile):
job.Job.__init__(self, agent_obj)
assert os.path.isfile(logfile), "Not a file: %s" % str(logfile)
self._log_size = os.stat(logfile).st_size
log.debug("Log size is %d" % self._log_size)
self._logfile_path = logfile
self._logfile_hndl = open(logfile, 'r')
self._progress = 0 # Data read from file
self._db = db_interface.getDB()
def <|fim_middle|>(self):
return self._logfile_path
def getBytesRead(self):
return self._progress
def getBytesTotal(self):
return self._log_size
def run(self):
evt = ReadLogContinueEvent(self)
self.getAgent().addEvent(evt)
def notify(self, evt):
job.Job.notify(self, evt)
if isinstance(evt, ReadLogContinueEvent) and evt.getSource() == self:
log.debug("Continuing read of file")
# Continue to read the log
try:
self._progress += log_parser.read_log(
self._logfile_hndl, self._db, LINEINCR)
log.debug("Read %d %% of file (%d / %d)" % (self.getProgress(),
self._progress,
self._log_size))
except log_parser.EndOfLogException, e:
self._progress = self._log_size
# Log file is complete, updated the db entry
self._mark_complete()
# Add an event to notify that the file is complete
self._logfile_hndl.close()
new_evt = ReadLogCompleteEvent(self)
self.getAgent().addEvent(new_evt)
except log_parser.InvalidLogException, e:
log.warning("Invalid log file: %s" % str(e))
self._logfile_hndl.close()
new_evt = ReadLogCompleteEvent(self)
self.getAgent().addEvent(new_evt)
else:
# Add an event to continue reading
new_evt = ReadLogContinueEvent(self)
self.getAgent().addEvent(new_evt)
def _update_db(self):
"""Update the entry in the database for this logfile"""
log.debug("Updating file %s" % self._logfile_path)
pass
def _mark_invalid(self):
"""Update the database to indicate that this is not a valid log file"""
log.debug("Marking file %s invalid" % self._logfile_path)
pass
def _mark_complete(self):
log.debug("Marking file %s complete" % self._logfile_path)
pass
def getProgress(self):
"""Return a percentage complete value"""
if self._log_size == 0:
return 0
return int((float(self._progress) / self._log_size) * 100)
<|fim▁end|> | getFilePath |
<|file_name|>read_job.py<|end_file_name|><|fim▁begin|># JoeTraffic - Web-Log Analysis Application utilizing the JoeAgent Framework.
# Copyright (C) 2004 Rhett Garber
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
from JoeAgent import job, event
import db_interface
import os, os.path
import logging
import log_parser
LINEINCR = 30
log = logging.getLogger("agent.LogReader")
class ReadLogCompleteEvent(event.Event):
"""Event to indicate the file is completely read. This event will
be caught by the FindLogJob that is watching it. The file will
continue to be checked for modifications"""
pass
class ReadLogContinueEvent(event.Event):
"""Event to indicate we should continue reading the file. Log file
processing will be done in chunks so as not to block the agent for
too long."""
pass
class ReadLogJob(job.Job):
def __init__(self, agent_obj, logfile):
job.Job.__init__(self, agent_obj)
assert os.path.isfile(logfile), "Not a file: %s" % str(logfile)
self._log_size = os.stat(logfile).st_size
log.debug("Log size is %d" % self._log_size)
self._logfile_path = logfile
self._logfile_hndl = open(logfile, 'r')
self._progress = 0 # Data read from file
self._db = db_interface.getDB()
def getFilePath(self):
return self._logfile_path
def <|fim_middle|>(self):
return self._progress
def getBytesTotal(self):
return self._log_size
def run(self):
evt = ReadLogContinueEvent(self)
self.getAgent().addEvent(evt)
def notify(self, evt):
job.Job.notify(self, evt)
if isinstance(evt, ReadLogContinueEvent) and evt.getSource() == self:
log.debug("Continuing read of file")
# Continue to read the log
try:
self._progress += log_parser.read_log(
self._logfile_hndl, self._db, LINEINCR)
log.debug("Read %d %% of file (%d / %d)" % (self.getProgress(),
self._progress,
self._log_size))
except log_parser.EndOfLogException, e:
self._progress = self._log_size
# Log file is complete, updated the db entry
self._mark_complete()
# Add an event to notify that the file is complete
self._logfile_hndl.close()
new_evt = ReadLogCompleteEvent(self)
self.getAgent().addEvent(new_evt)
except log_parser.InvalidLogException, e:
log.warning("Invalid log file: %s" % str(e))
self._logfile_hndl.close()
new_evt = ReadLogCompleteEvent(self)
self.getAgent().addEvent(new_evt)
else:
# Add an event to continue reading
new_evt = ReadLogContinueEvent(self)
self.getAgent().addEvent(new_evt)
def _update_db(self):
"""Update the entry in the database for this logfile"""
log.debug("Updating file %s" % self._logfile_path)
pass
def _mark_invalid(self):
"""Update the database to indicate that this is not a valid log file"""
log.debug("Marking file %s invalid" % self._logfile_path)
pass
def _mark_complete(self):
log.debug("Marking file %s complete" % self._logfile_path)
pass
def getProgress(self):
"""Return a percentage complete value"""
if self._log_size == 0:
return 0
return int((float(self._progress) / self._log_size) * 100)
<|fim▁end|> | getBytesRead |
<|file_name|>read_job.py<|end_file_name|><|fim▁begin|># JoeTraffic - Web-Log Analysis Application utilizing the JoeAgent Framework.
# Copyright (C) 2004 Rhett Garber
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
from JoeAgent import job, event
import db_interface
import os, os.path
import logging
import log_parser
LINEINCR = 30
log = logging.getLogger("agent.LogReader")
class ReadLogCompleteEvent(event.Event):
"""Event to indicate the file is completely read. This event will
be caught by the FindLogJob that is watching it. The file will
continue to be checked for modifications"""
pass
class ReadLogContinueEvent(event.Event):
"""Event to indicate we should continue reading the file. Log file
processing will be done in chunks so as not to block the agent for
too long."""
pass
class ReadLogJob(job.Job):
def __init__(self, agent_obj, logfile):
job.Job.__init__(self, agent_obj)
assert os.path.isfile(logfile), "Not a file: %s" % str(logfile)
self._log_size = os.stat(logfile).st_size
log.debug("Log size is %d" % self._log_size)
self._logfile_path = logfile
self._logfile_hndl = open(logfile, 'r')
self._progress = 0 # Data read from file
self._db = db_interface.getDB()
def getFilePath(self):
return self._logfile_path
def getBytesRead(self):
return self._progress
def <|fim_middle|>(self):
return self._log_size
def run(self):
evt = ReadLogContinueEvent(self)
self.getAgent().addEvent(evt)
def notify(self, evt):
job.Job.notify(self, evt)
if isinstance(evt, ReadLogContinueEvent) and evt.getSource() == self:
log.debug("Continuing read of file")
# Continue to read the log
try:
self._progress += log_parser.read_log(
self._logfile_hndl, self._db, LINEINCR)
log.debug("Read %d %% of file (%d / %d)" % (self.getProgress(),
self._progress,
self._log_size))
except log_parser.EndOfLogException, e:
self._progress = self._log_size
# Log file is complete, updated the db entry
self._mark_complete()
# Add an event to notify that the file is complete
self._logfile_hndl.close()
new_evt = ReadLogCompleteEvent(self)
self.getAgent().addEvent(new_evt)
except log_parser.InvalidLogException, e:
log.warning("Invalid log file: %s" % str(e))
self._logfile_hndl.close()
new_evt = ReadLogCompleteEvent(self)
self.getAgent().addEvent(new_evt)
else:
# Add an event to continue reading
new_evt = ReadLogContinueEvent(self)
self.getAgent().addEvent(new_evt)
def _update_db(self):
"""Update the entry in the database for this logfile"""
log.debug("Updating file %s" % self._logfile_path)
pass
def _mark_invalid(self):
"""Update the database to indicate that this is not a valid log file"""
log.debug("Marking file %s invalid" % self._logfile_path)
pass
def _mark_complete(self):
log.debug("Marking file %s complete" % self._logfile_path)
pass
def getProgress(self):
"""Return a percentage complete value"""
if self._log_size == 0:
return 0
return int((float(self._progress) / self._log_size) * 100)
<|fim▁end|> | getBytesTotal |
<|file_name|>read_job.py<|end_file_name|><|fim▁begin|># JoeTraffic - Web-Log Analysis Application utilizing the JoeAgent Framework.
# Copyright (C) 2004 Rhett Garber
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
from JoeAgent import job, event
import db_interface
import os, os.path
import logging
import log_parser
LINEINCR = 30
log = logging.getLogger("agent.LogReader")
class ReadLogCompleteEvent(event.Event):
"""Event to indicate the file is completely read. This event will
be caught by the FindLogJob that is watching it. The file will
continue to be checked for modifications"""
pass
class ReadLogContinueEvent(event.Event):
"""Event to indicate we should continue reading the file. Log file
processing will be done in chunks so as not to block the agent for
too long."""
pass
class ReadLogJob(job.Job):
def __init__(self, agent_obj, logfile):
job.Job.__init__(self, agent_obj)
assert os.path.isfile(logfile), "Not a file: %s" % str(logfile)
self._log_size = os.stat(logfile).st_size
log.debug("Log size is %d" % self._log_size)
self._logfile_path = logfile
self._logfile_hndl = open(logfile, 'r')
self._progress = 0 # Data read from file
self._db = db_interface.getDB()
def getFilePath(self):
return self._logfile_path
def getBytesRead(self):
return self._progress
def getBytesTotal(self):
return self._log_size
def <|fim_middle|>(self):
evt = ReadLogContinueEvent(self)
self.getAgent().addEvent(evt)
def notify(self, evt):
job.Job.notify(self, evt)
if isinstance(evt, ReadLogContinueEvent) and evt.getSource() == self:
log.debug("Continuing read of file")
# Continue to read the log
try:
self._progress += log_parser.read_log(
self._logfile_hndl, self._db, LINEINCR)
log.debug("Read %d %% of file (%d / %d)" % (self.getProgress(),
self._progress,
self._log_size))
except log_parser.EndOfLogException, e:
self._progress = self._log_size
# Log file is complete, updated the db entry
self._mark_complete()
# Add an event to notify that the file is complete
self._logfile_hndl.close()
new_evt = ReadLogCompleteEvent(self)
self.getAgent().addEvent(new_evt)
except log_parser.InvalidLogException, e:
log.warning("Invalid log file: %s" % str(e))
self._logfile_hndl.close()
new_evt = ReadLogCompleteEvent(self)
self.getAgent().addEvent(new_evt)
else:
# Add an event to continue reading
new_evt = ReadLogContinueEvent(self)
self.getAgent().addEvent(new_evt)
def _update_db(self):
"""Update the entry in the database for this logfile"""
log.debug("Updating file %s" % self._logfile_path)
pass
def _mark_invalid(self):
"""Update the database to indicate that this is not a valid log file"""
log.debug("Marking file %s invalid" % self._logfile_path)
pass
def _mark_complete(self):
log.debug("Marking file %s complete" % self._logfile_path)
pass
def getProgress(self):
"""Return a percentage complete value"""
if self._log_size == 0:
return 0
return int((float(self._progress) / self._log_size) * 100)
<|fim▁end|> | run |
<|file_name|>read_job.py<|end_file_name|><|fim▁begin|># JoeTraffic - Web-Log Analysis Application utilizing the JoeAgent Framework.
# Copyright (C) 2004 Rhett Garber
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
from JoeAgent import job, event
import db_interface
import os, os.path
import logging
import log_parser
LINEINCR = 30
log = logging.getLogger("agent.LogReader")
class ReadLogCompleteEvent(event.Event):
"""Event to indicate the file is completely read. This event will
be caught by the FindLogJob that is watching it. The file will
continue to be checked for modifications"""
pass
class ReadLogContinueEvent(event.Event):
"""Event to indicate we should continue reading the file. Log file
processing will be done in chunks so as not to block the agent for
too long."""
pass
class ReadLogJob(job.Job):
def __init__(self, agent_obj, logfile):
job.Job.__init__(self, agent_obj)
assert os.path.isfile(logfile), "Not a file: %s" % str(logfile)
self._log_size = os.stat(logfile).st_size
log.debug("Log size is %d" % self._log_size)
self._logfile_path = logfile
self._logfile_hndl = open(logfile, 'r')
self._progress = 0 # Data read from file
self._db = db_interface.getDB()
def getFilePath(self):
return self._logfile_path
def getBytesRead(self):
return self._progress
def getBytesTotal(self):
return self._log_size
def run(self):
evt = ReadLogContinueEvent(self)
self.getAgent().addEvent(evt)
def <|fim_middle|>(self, evt):
job.Job.notify(self, evt)
if isinstance(evt, ReadLogContinueEvent) and evt.getSource() == self:
log.debug("Continuing read of file")
# Continue to read the log
try:
self._progress += log_parser.read_log(
self._logfile_hndl, self._db, LINEINCR)
log.debug("Read %d %% of file (%d / %d)" % (self.getProgress(),
self._progress,
self._log_size))
except log_parser.EndOfLogException, e:
self._progress = self._log_size
# Log file is complete, updated the db entry
self._mark_complete()
# Add an event to notify that the file is complete
self._logfile_hndl.close()
new_evt = ReadLogCompleteEvent(self)
self.getAgent().addEvent(new_evt)
except log_parser.InvalidLogException, e:
log.warning("Invalid log file: %s" % str(e))
self._logfile_hndl.close()
new_evt = ReadLogCompleteEvent(self)
self.getAgent().addEvent(new_evt)
else:
# Add an event to continue reading
new_evt = ReadLogContinueEvent(self)
self.getAgent().addEvent(new_evt)
def _update_db(self):
"""Update the entry in the database for this logfile"""
log.debug("Updating file %s" % self._logfile_path)
pass
def _mark_invalid(self):
"""Update the database to indicate that this is not a valid log file"""
log.debug("Marking file %s invalid" % self._logfile_path)
pass
def _mark_complete(self):
log.debug("Marking file %s complete" % self._logfile_path)
pass
def getProgress(self):
"""Return a percentage complete value"""
if self._log_size == 0:
return 0
return int((float(self._progress) / self._log_size) * 100)
<|fim▁end|> | notify |
<|file_name|>read_job.py<|end_file_name|><|fim▁begin|># JoeTraffic - Web-Log Analysis Application utilizing the JoeAgent Framework.
# Copyright (C) 2004 Rhett Garber
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
from JoeAgent import job, event
import db_interface
import os, os.path
import logging
import log_parser
LINEINCR = 30
log = logging.getLogger("agent.LogReader")
class ReadLogCompleteEvent(event.Event):
"""Event to indicate the file is completely read. This event will
be caught by the FindLogJob that is watching it. The file will
continue to be checked for modifications"""
pass
class ReadLogContinueEvent(event.Event):
"""Event to indicate we should continue reading the file. Log file
processing will be done in chunks so as not to block the agent for
too long."""
pass
class ReadLogJob(job.Job):
def __init__(self, agent_obj, logfile):
job.Job.__init__(self, agent_obj)
assert os.path.isfile(logfile), "Not a file: %s" % str(logfile)
self._log_size = os.stat(logfile).st_size
log.debug("Log size is %d" % self._log_size)
self._logfile_path = logfile
self._logfile_hndl = open(logfile, 'r')
self._progress = 0 # Data read from file
self._db = db_interface.getDB()
def getFilePath(self):
return self._logfile_path
def getBytesRead(self):
return self._progress
def getBytesTotal(self):
return self._log_size
def run(self):
evt = ReadLogContinueEvent(self)
self.getAgent().addEvent(evt)
def notify(self, evt):
job.Job.notify(self, evt)
if isinstance(evt, ReadLogContinueEvent) and evt.getSource() == self:
log.debug("Continuing read of file")
# Continue to read the log
try:
self._progress += log_parser.read_log(
self._logfile_hndl, self._db, LINEINCR)
log.debug("Read %d %% of file (%d / %d)" % (self.getProgress(),
self._progress,
self._log_size))
except log_parser.EndOfLogException, e:
self._progress = self._log_size
# Log file is complete, updated the db entry
self._mark_complete()
# Add an event to notify that the file is complete
self._logfile_hndl.close()
new_evt = ReadLogCompleteEvent(self)
self.getAgent().addEvent(new_evt)
except log_parser.InvalidLogException, e:
log.warning("Invalid log file: %s" % str(e))
self._logfile_hndl.close()
new_evt = ReadLogCompleteEvent(self)
self.getAgent().addEvent(new_evt)
else:
# Add an event to continue reading
new_evt = ReadLogContinueEvent(self)
self.getAgent().addEvent(new_evt)
def <|fim_middle|>(self):
"""Update the entry in the database for this logfile"""
log.debug("Updating file %s" % self._logfile_path)
pass
def _mark_invalid(self):
"""Update the database to indicate that this is not a valid log file"""
log.debug("Marking file %s invalid" % self._logfile_path)
pass
def _mark_complete(self):
log.debug("Marking file %s complete" % self._logfile_path)
pass
def getProgress(self):
"""Return a percentage complete value"""
if self._log_size == 0:
return 0
return int((float(self._progress) / self._log_size) * 100)
<|fim▁end|> | _update_db |
<|file_name|>read_job.py<|end_file_name|><|fim▁begin|># JoeTraffic - Web-Log Analysis Application utilizing the JoeAgent Framework.
# Copyright (C) 2004 Rhett Garber
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
from JoeAgent import job, event
import db_interface
import os, os.path
import logging
import log_parser
LINEINCR = 30
log = logging.getLogger("agent.LogReader")
class ReadLogCompleteEvent(event.Event):
"""Event to indicate the file is completely read. This event will
be caught by the FindLogJob that is watching it. The file will
continue to be checked for modifications"""
pass
class ReadLogContinueEvent(event.Event):
"""Event to indicate we should continue reading the file. Log file
processing will be done in chunks so as not to block the agent for
too long."""
pass
class ReadLogJob(job.Job):
def __init__(self, agent_obj, logfile):
job.Job.__init__(self, agent_obj)
assert os.path.isfile(logfile), "Not a file: %s" % str(logfile)
self._log_size = os.stat(logfile).st_size
log.debug("Log size is %d" % self._log_size)
self._logfile_path = logfile
self._logfile_hndl = open(logfile, 'r')
self._progress = 0 # Data read from file
self._db = db_interface.getDB()
def getFilePath(self):
return self._logfile_path
def getBytesRead(self):
return self._progress
def getBytesTotal(self):
return self._log_size
def run(self):
evt = ReadLogContinueEvent(self)
self.getAgent().addEvent(evt)
def notify(self, evt):
job.Job.notify(self, evt)
if isinstance(evt, ReadLogContinueEvent) and evt.getSource() == self:
log.debug("Continuing read of file")
# Continue to read the log
try:
self._progress += log_parser.read_log(
self._logfile_hndl, self._db, LINEINCR)
log.debug("Read %d %% of file (%d / %d)" % (self.getProgress(),
self._progress,
self._log_size))
except log_parser.EndOfLogException, e:
self._progress = self._log_size
# Log file is complete, updated the db entry
self._mark_complete()
# Add an event to notify that the file is complete
self._logfile_hndl.close()
new_evt = ReadLogCompleteEvent(self)
self.getAgent().addEvent(new_evt)
except log_parser.InvalidLogException, e:
log.warning("Invalid log file: %s" % str(e))
self._logfile_hndl.close()
new_evt = ReadLogCompleteEvent(self)
self.getAgent().addEvent(new_evt)
else:
# Add an event to continue reading
new_evt = ReadLogContinueEvent(self)
self.getAgent().addEvent(new_evt)
def _update_db(self):
"""Update the entry in the database for this logfile"""
log.debug("Updating file %s" % self._logfile_path)
pass
def <|fim_middle|>(self):
"""Update the database to indicate that this is not a valid log file"""
log.debug("Marking file %s invalid" % self._logfile_path)
pass
def _mark_complete(self):
log.debug("Marking file %s complete" % self._logfile_path)
pass
def getProgress(self):
"""Return a percentage complete value"""
if self._log_size == 0:
return 0
return int((float(self._progress) / self._log_size) * 100)
<|fim▁end|> | _mark_invalid |
<|file_name|>read_job.py<|end_file_name|><|fim▁begin|># JoeTraffic - Web-Log Analysis Application utilizing the JoeAgent Framework.
# Copyright (C) 2004 Rhett Garber
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
from JoeAgent import job, event
import db_interface
import os, os.path
import logging
import log_parser
LINEINCR = 30
log = logging.getLogger("agent.LogReader")
class ReadLogCompleteEvent(event.Event):
"""Event to indicate the file is completely read. This event will
be caught by the FindLogJob that is watching it. The file will
continue to be checked for modifications"""
pass
class ReadLogContinueEvent(event.Event):
"""Event to indicate we should continue reading the file. Log file
processing will be done in chunks so as not to block the agent for
too long."""
pass
class ReadLogJob(job.Job):
def __init__(self, agent_obj, logfile):
job.Job.__init__(self, agent_obj)
assert os.path.isfile(logfile), "Not a file: %s" % str(logfile)
self._log_size = os.stat(logfile).st_size
log.debug("Log size is %d" % self._log_size)
self._logfile_path = logfile
self._logfile_hndl = open(logfile, 'r')
self._progress = 0 # Data read from file
self._db = db_interface.getDB()
def getFilePath(self):
return self._logfile_path
def getBytesRead(self):
return self._progress
def getBytesTotal(self):
return self._log_size
def run(self):
evt = ReadLogContinueEvent(self)
self.getAgent().addEvent(evt)
def notify(self, evt):
job.Job.notify(self, evt)
if isinstance(evt, ReadLogContinueEvent) and evt.getSource() == self:
log.debug("Continuing read of file")
# Continue to read the log
try:
self._progress += log_parser.read_log(
self._logfile_hndl, self._db, LINEINCR)
log.debug("Read %d %% of file (%d / %d)" % (self.getProgress(),
self._progress,
self._log_size))
except log_parser.EndOfLogException, e:
self._progress = self._log_size
# Log file is complete, updated the db entry
self._mark_complete()
# Add an event to notify that the file is complete
self._logfile_hndl.close()
new_evt = ReadLogCompleteEvent(self)
self.getAgent().addEvent(new_evt)
except log_parser.InvalidLogException, e:
log.warning("Invalid log file: %s" % str(e))
self._logfile_hndl.close()
new_evt = ReadLogCompleteEvent(self)
self.getAgent().addEvent(new_evt)
else:
# Add an event to continue reading
new_evt = ReadLogContinueEvent(self)
self.getAgent().addEvent(new_evt)
def _update_db(self):
"""Update the entry in the database for this logfile"""
log.debug("Updating file %s" % self._logfile_path)
pass
def _mark_invalid(self):
"""Update the database to indicate that this is not a valid log file"""
log.debug("Marking file %s invalid" % self._logfile_path)
pass
def <|fim_middle|>(self):
log.debug("Marking file %s complete" % self._logfile_path)
pass
def getProgress(self):
"""Return a percentage complete value"""
if self._log_size == 0:
return 0
return int((float(self._progress) / self._log_size) * 100)
<|fim▁end|> | _mark_complete |
<|file_name|>read_job.py<|end_file_name|><|fim▁begin|># JoeTraffic - Web-Log Analysis Application utilizing the JoeAgent Framework.
# Copyright (C) 2004 Rhett Garber
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
from JoeAgent import job, event
import db_interface
import os, os.path
import logging
import log_parser
LINEINCR = 30
log = logging.getLogger("agent.LogReader")
class ReadLogCompleteEvent(event.Event):
"""Event to indicate the file is completely read. This event will
be caught by the FindLogJob that is watching it. The file will
continue to be checked for modifications"""
pass
class ReadLogContinueEvent(event.Event):
"""Event to indicate we should continue reading the file. Log file
processing will be done in chunks so as not to block the agent for
too long."""
pass
class ReadLogJob(job.Job):
def __init__(self, agent_obj, logfile):
job.Job.__init__(self, agent_obj)
assert os.path.isfile(logfile), "Not a file: %s" % str(logfile)
self._log_size = os.stat(logfile).st_size
log.debug("Log size is %d" % self._log_size)
self._logfile_path = logfile
self._logfile_hndl = open(logfile, 'r')
self._progress = 0 # Data read from file
self._db = db_interface.getDB()
def getFilePath(self):
return self._logfile_path
def getBytesRead(self):
return self._progress
def getBytesTotal(self):
return self._log_size
def run(self):
evt = ReadLogContinueEvent(self)
self.getAgent().addEvent(evt)
def notify(self, evt):
job.Job.notify(self, evt)
if isinstance(evt, ReadLogContinueEvent) and evt.getSource() == self:
log.debug("Continuing read of file")
# Continue to read the log
try:
self._progress += log_parser.read_log(
self._logfile_hndl, self._db, LINEINCR)
log.debug("Read %d %% of file (%d / %d)" % (self.getProgress(),
self._progress,
self._log_size))
except log_parser.EndOfLogException, e:
self._progress = self._log_size
# Log file is complete, updated the db entry
self._mark_complete()
# Add an event to notify that the file is complete
self._logfile_hndl.close()
new_evt = ReadLogCompleteEvent(self)
self.getAgent().addEvent(new_evt)
except log_parser.InvalidLogException, e:
log.warning("Invalid log file: %s" % str(e))
self._logfile_hndl.close()
new_evt = ReadLogCompleteEvent(self)
self.getAgent().addEvent(new_evt)
else:
# Add an event to continue reading
new_evt = ReadLogContinueEvent(self)
self.getAgent().addEvent(new_evt)
def _update_db(self):
"""Update the entry in the database for this logfile"""
log.debug("Updating file %s" % self._logfile_path)
pass
def _mark_invalid(self):
"""Update the database to indicate that this is not a valid log file"""
log.debug("Marking file %s invalid" % self._logfile_path)
pass
def _mark_complete(self):
log.debug("Marking file %s complete" % self._logfile_path)
pass
def <|fim_middle|>(self):
"""Return a percentage complete value"""
if self._log_size == 0:
return 0
return int((float(self._progress) / self._log_size) * 100)
<|fim▁end|> | getProgress |
<|file_name|>test_logging_support.py<|end_file_name|><|fim▁begin|>#
# LMirror is Copyright (C) 2010 Robert Collins <[email protected]>
#
# LMirror is free software: you can redistribute it and/or modify it under the
# terms of the GNU General Public License as published by the Free Software
# Foundation, either version 3 of the License, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
# PARTICULAR PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with
# this program. If not, see <http://www.gnu.org/licenses/>.
#
# In the LMirror source tree the file COPYING.txt contains the GNU General Public
# License version 3.
#
"""Tests for logging support code."""
from StringIO import StringIO
import logging
import os.path
import time
from l_mirror import logging_support
from l_mirror.tests import ResourcedTestCase
from l_mirror.tests.logging_resource import LoggingResourceManager
from l_mirror.tests.stubpackage import TempDirResource
<|fim▁hole|>class TestLoggingSetup(ResourcedTestCase):
resources = [('logging', LoggingResourceManager())]
def test_configure_logging_sets_converter(self):
out = StringIO()
c_log, f_log, formatter = logging_support.configure_logging(out)
self.assertEqual(c_log, logging.root.handlers[0])
self.assertEqual(f_log, logging.root.handlers[1])
self.assertEqual(None, c_log.formatter)
self.assertEqual(formatter, f_log.formatter)
self.assertEqual(time.gmtime, formatter.converter)
self.assertEqual("%Y-%m-%d %H:%M:%SZ", formatter.datefmt)
self.assertEqual(logging.StreamHandler, c_log.__class__)
self.assertEqual(out, c_log.stream)
self.assertEqual(logging.FileHandler, f_log.__class__)
self.assertEqual(os.path.expanduser("~/.cache/lmirror/log"), f_log.baseFilename)
def test_can_supply_filename_None(self):
out = StringIO()
c_log, f_log, formatter = logging_support.configure_logging(out, None)
self.assertEqual(None, f_log)<|fim▁end|> | |
<|file_name|>test_logging_support.py<|end_file_name|><|fim▁begin|>#
# LMirror is Copyright (C) 2010 Robert Collins <[email protected]>
#
# LMirror is free software: you can redistribute it and/or modify it under the
# terms of the GNU General Public License as published by the Free Software
# Foundation, either version 3 of the License, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
# PARTICULAR PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with
# this program. If not, see <http://www.gnu.org/licenses/>.
#
# In the LMirror source tree the file COPYING.txt contains the GNU General Public
# License version 3.
#
"""Tests for logging support code."""
from StringIO import StringIO
import logging
import os.path
import time
from l_mirror import logging_support
from l_mirror.tests import ResourcedTestCase
from l_mirror.tests.logging_resource import LoggingResourceManager
from l_mirror.tests.stubpackage import TempDirResource
class TestLoggingSetup(ResourcedTestCase):
<|fim_middle|>
<|fim▁end|> | resources = [('logging', LoggingResourceManager())]
def test_configure_logging_sets_converter(self):
out = StringIO()
c_log, f_log, formatter = logging_support.configure_logging(out)
self.assertEqual(c_log, logging.root.handlers[0])
self.assertEqual(f_log, logging.root.handlers[1])
self.assertEqual(None, c_log.formatter)
self.assertEqual(formatter, f_log.formatter)
self.assertEqual(time.gmtime, formatter.converter)
self.assertEqual("%Y-%m-%d %H:%M:%SZ", formatter.datefmt)
self.assertEqual(logging.StreamHandler, c_log.__class__)
self.assertEqual(out, c_log.stream)
self.assertEqual(logging.FileHandler, f_log.__class__)
self.assertEqual(os.path.expanduser("~/.cache/lmirror/log"), f_log.baseFilename)
def test_can_supply_filename_None(self):
out = StringIO()
c_log, f_log, formatter = logging_support.configure_logging(out, None)
self.assertEqual(None, f_log) |
<|file_name|>test_logging_support.py<|end_file_name|><|fim▁begin|>#
# LMirror is Copyright (C) 2010 Robert Collins <[email protected]>
#
# LMirror is free software: you can redistribute it and/or modify it under the
# terms of the GNU General Public License as published by the Free Software
# Foundation, either version 3 of the License, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
# PARTICULAR PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with
# this program. If not, see <http://www.gnu.org/licenses/>.
#
# In the LMirror source tree the file COPYING.txt contains the GNU General Public
# License version 3.
#
"""Tests for logging support code."""
from StringIO import StringIO
import logging
import os.path
import time
from l_mirror import logging_support
from l_mirror.tests import ResourcedTestCase
from l_mirror.tests.logging_resource import LoggingResourceManager
from l_mirror.tests.stubpackage import TempDirResource
class TestLoggingSetup(ResourcedTestCase):
resources = [('logging', LoggingResourceManager())]
def test_configure_logging_sets_converter(self):
<|fim_middle|>
def test_can_supply_filename_None(self):
out = StringIO()
c_log, f_log, formatter = logging_support.configure_logging(out, None)
self.assertEqual(None, f_log)
<|fim▁end|> | out = StringIO()
c_log, f_log, formatter = logging_support.configure_logging(out)
self.assertEqual(c_log, logging.root.handlers[0])
self.assertEqual(f_log, logging.root.handlers[1])
self.assertEqual(None, c_log.formatter)
self.assertEqual(formatter, f_log.formatter)
self.assertEqual(time.gmtime, formatter.converter)
self.assertEqual("%Y-%m-%d %H:%M:%SZ", formatter.datefmt)
self.assertEqual(logging.StreamHandler, c_log.__class__)
self.assertEqual(out, c_log.stream)
self.assertEqual(logging.FileHandler, f_log.__class__)
self.assertEqual(os.path.expanduser("~/.cache/lmirror/log"), f_log.baseFilename) |
<|file_name|>test_logging_support.py<|end_file_name|><|fim▁begin|>#
# LMirror is Copyright (C) 2010 Robert Collins <[email protected]>
#
# LMirror is free software: you can redistribute it and/or modify it under the
# terms of the GNU General Public License as published by the Free Software
# Foundation, either version 3 of the License, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
# PARTICULAR PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with
# this program. If not, see <http://www.gnu.org/licenses/>.
#
# In the LMirror source tree the file COPYING.txt contains the GNU General Public
# License version 3.
#
"""Tests for logging support code."""
from StringIO import StringIO
import logging
import os.path
import time
from l_mirror import logging_support
from l_mirror.tests import ResourcedTestCase
from l_mirror.tests.logging_resource import LoggingResourceManager
from l_mirror.tests.stubpackage import TempDirResource
class TestLoggingSetup(ResourcedTestCase):
resources = [('logging', LoggingResourceManager())]
def test_configure_logging_sets_converter(self):
out = StringIO()
c_log, f_log, formatter = logging_support.configure_logging(out)
self.assertEqual(c_log, logging.root.handlers[0])
self.assertEqual(f_log, logging.root.handlers[1])
self.assertEqual(None, c_log.formatter)
self.assertEqual(formatter, f_log.formatter)
self.assertEqual(time.gmtime, formatter.converter)
self.assertEqual("%Y-%m-%d %H:%M:%SZ", formatter.datefmt)
self.assertEqual(logging.StreamHandler, c_log.__class__)
self.assertEqual(out, c_log.stream)
self.assertEqual(logging.FileHandler, f_log.__class__)
self.assertEqual(os.path.expanduser("~/.cache/lmirror/log"), f_log.baseFilename)
def test_can_supply_filename_None(self):
<|fim_middle|>
<|fim▁end|> | out = StringIO()
c_log, f_log, formatter = logging_support.configure_logging(out, None)
self.assertEqual(None, f_log) |
<|file_name|>test_logging_support.py<|end_file_name|><|fim▁begin|>#
# LMirror is Copyright (C) 2010 Robert Collins <[email protected]>
#
# LMirror is free software: you can redistribute it and/or modify it under the
# terms of the GNU General Public License as published by the Free Software
# Foundation, either version 3 of the License, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
# PARTICULAR PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with
# this program. If not, see <http://www.gnu.org/licenses/>.
#
# In the LMirror source tree the file COPYING.txt contains the GNU General Public
# License version 3.
#
"""Tests for logging support code."""
from StringIO import StringIO
import logging
import os.path
import time
from l_mirror import logging_support
from l_mirror.tests import ResourcedTestCase
from l_mirror.tests.logging_resource import LoggingResourceManager
from l_mirror.tests.stubpackage import TempDirResource
class TestLoggingSetup(ResourcedTestCase):
resources = [('logging', LoggingResourceManager())]
def <|fim_middle|>(self):
out = StringIO()
c_log, f_log, formatter = logging_support.configure_logging(out)
self.assertEqual(c_log, logging.root.handlers[0])
self.assertEqual(f_log, logging.root.handlers[1])
self.assertEqual(None, c_log.formatter)
self.assertEqual(formatter, f_log.formatter)
self.assertEqual(time.gmtime, formatter.converter)
self.assertEqual("%Y-%m-%d %H:%M:%SZ", formatter.datefmt)
self.assertEqual(logging.StreamHandler, c_log.__class__)
self.assertEqual(out, c_log.stream)
self.assertEqual(logging.FileHandler, f_log.__class__)
self.assertEqual(os.path.expanduser("~/.cache/lmirror/log"), f_log.baseFilename)
def test_can_supply_filename_None(self):
out = StringIO()
c_log, f_log, formatter = logging_support.configure_logging(out, None)
self.assertEqual(None, f_log)
<|fim▁end|> | test_configure_logging_sets_converter |
<|file_name|>test_logging_support.py<|end_file_name|><|fim▁begin|>#
# LMirror is Copyright (C) 2010 Robert Collins <[email protected]>
#
# LMirror is free software: you can redistribute it and/or modify it under the
# terms of the GNU General Public License as published by the Free Software
# Foundation, either version 3 of the License, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
# PARTICULAR PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with
# this program. If not, see <http://www.gnu.org/licenses/>.
#
# In the LMirror source tree the file COPYING.txt contains the GNU General Public
# License version 3.
#
"""Tests for logging support code."""
from StringIO import StringIO
import logging
import os.path
import time
from l_mirror import logging_support
from l_mirror.tests import ResourcedTestCase
from l_mirror.tests.logging_resource import LoggingResourceManager
from l_mirror.tests.stubpackage import TempDirResource
class TestLoggingSetup(ResourcedTestCase):
resources = [('logging', LoggingResourceManager())]
def test_configure_logging_sets_converter(self):
out = StringIO()
c_log, f_log, formatter = logging_support.configure_logging(out)
self.assertEqual(c_log, logging.root.handlers[0])
self.assertEqual(f_log, logging.root.handlers[1])
self.assertEqual(None, c_log.formatter)
self.assertEqual(formatter, f_log.formatter)
self.assertEqual(time.gmtime, formatter.converter)
self.assertEqual("%Y-%m-%d %H:%M:%SZ", formatter.datefmt)
self.assertEqual(logging.StreamHandler, c_log.__class__)
self.assertEqual(out, c_log.stream)
self.assertEqual(logging.FileHandler, f_log.__class__)
self.assertEqual(os.path.expanduser("~/.cache/lmirror/log"), f_log.baseFilename)
def <|fim_middle|>(self):
out = StringIO()
c_log, f_log, formatter = logging_support.configure_logging(out, None)
self.assertEqual(None, f_log)
<|fim▁end|> | test_can_supply_filename_None |
<|file_name|>loaders.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# ####################################################################
# Copyright (C) 2005-2019 by the FIFE team
# http://www.fifengine.net
# This file is part of FIFE.
#
# FIFE is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
# ####################################################################
""" Loaders plugin manager """
from __future__ import print_function
import os.path
from fife import fife
from fife.extensions.serializers.xmlmap import XMLMapLoader
mapFileMapping = { 'xml' : XMLMapLoader}
fileExtensions = set(['xml'])
def loadMapFile(path, engine, callback=None, debug=True, extensions={}):
""" load map file and get (an optional) callback if major stuff is done:
- map creation
- parsed imports
- parsed layers
- parsed cameras
the callback will send both a string and a float (which shows
the overall process), callback(string, float)
<|fim▁hole|> @type engine: object
@param engine: FIFE engine instance
@type callback: function
@param callback: callback for maploading progress
@type debug: bool
@param debug: flag to activate / deactivate print statements
@rtype object
@return FIFE map object
"""
(filename, extension) = os.path.splitext(path)
map_loader = mapFileMapping[extension[1:]](engine, callback, debug, extensions)
map = map_loader.loadResource(path)
if debug: print("--- Loading map took: ", map_loader.time_to_load, " seconds.")
return map
def addMapLoader(fileExtension, loaderClass):
"""Add a new loader for fileextension
@type fileExtension: string
@param fileExtension: The file extension the loader is registered for
@type loaderClass: object
@param loaderClass: A fife.ResourceLoader implementation that loads maps
from files with the given fileExtension
"""
mapFileMapping[fileExtension] = loaderClass
_updateMapFileExtensions()
def _updateMapFileExtensions():
global fileExtensions
fileExtensions = set(mapFileMapping.keys())<|fim▁end|> | |
<|file_name|>loaders.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# ####################################################################
# Copyright (C) 2005-2019 by the FIFE team
# http://www.fifengine.net
# This file is part of FIFE.
#
# FIFE is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
# ####################################################################
""" Loaders plugin manager """
from __future__ import print_function
import os.path
from fife import fife
from fife.extensions.serializers.xmlmap import XMLMapLoader
mapFileMapping = { 'xml' : XMLMapLoader}
fileExtensions = set(['xml'])
def loadMapFile(path, engine, callback=None, debug=True, extensions={}):
<|fim_middle|>
def addMapLoader(fileExtension, loaderClass):
"""Add a new loader for fileextension
@type fileExtension: string
@param fileExtension: The file extension the loader is registered for
@type loaderClass: object
@param loaderClass: A fife.ResourceLoader implementation that loads maps
from files with the given fileExtension
"""
mapFileMapping[fileExtension] = loaderClass
_updateMapFileExtensions()
def _updateMapFileExtensions():
global fileExtensions
fileExtensions = set(mapFileMapping.keys())
<|fim▁end|> | """ load map file and get (an optional) callback if major stuff is done:
- map creation
- parsed imports
- parsed layers
- parsed cameras
the callback will send both a string and a float (which shows
the overall process), callback(string, float)
@type engine: object
@param engine: FIFE engine instance
@type callback: function
@param callback: callback for maploading progress
@type debug: bool
@param debug: flag to activate / deactivate print statements
@rtype object
@return FIFE map object
"""
(filename, extension) = os.path.splitext(path)
map_loader = mapFileMapping[extension[1:]](engine, callback, debug, extensions)
map = map_loader.loadResource(path)
if debug: print("--- Loading map took: ", map_loader.time_to_load, " seconds.")
return map |
<|file_name|>loaders.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# ####################################################################
# Copyright (C) 2005-2019 by the FIFE team
# http://www.fifengine.net
# This file is part of FIFE.
#
# FIFE is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
# ####################################################################
""" Loaders plugin manager """
from __future__ import print_function
import os.path
from fife import fife
from fife.extensions.serializers.xmlmap import XMLMapLoader
mapFileMapping = { 'xml' : XMLMapLoader}
fileExtensions = set(['xml'])
def loadMapFile(path, engine, callback=None, debug=True, extensions={}):
""" load map file and get (an optional) callback if major stuff is done:
- map creation
- parsed imports
- parsed layers
- parsed cameras
the callback will send both a string and a float (which shows
the overall process), callback(string, float)
@type engine: object
@param engine: FIFE engine instance
@type callback: function
@param callback: callback for maploading progress
@type debug: bool
@param debug: flag to activate / deactivate print statements
@rtype object
@return FIFE map object
"""
(filename, extension) = os.path.splitext(path)
map_loader = mapFileMapping[extension[1:]](engine, callback, debug, extensions)
map = map_loader.loadResource(path)
if debug: print("--- Loading map took: ", map_loader.time_to_load, " seconds.")
return map
def addMapLoader(fileExtension, loaderClass):
<|fim_middle|>
def _updateMapFileExtensions():
global fileExtensions
fileExtensions = set(mapFileMapping.keys())
<|fim▁end|> | """Add a new loader for fileextension
@type fileExtension: string
@param fileExtension: The file extension the loader is registered for
@type loaderClass: object
@param loaderClass: A fife.ResourceLoader implementation that loads maps
from files with the given fileExtension
"""
mapFileMapping[fileExtension] = loaderClass
_updateMapFileExtensions() |
<|file_name|>loaders.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# ####################################################################
# Copyright (C) 2005-2019 by the FIFE team
# http://www.fifengine.net
# This file is part of FIFE.
#
# FIFE is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
# ####################################################################
""" Loaders plugin manager """
from __future__ import print_function
import os.path
from fife import fife
from fife.extensions.serializers.xmlmap import XMLMapLoader
mapFileMapping = { 'xml' : XMLMapLoader}
fileExtensions = set(['xml'])
def loadMapFile(path, engine, callback=None, debug=True, extensions={}):
""" load map file and get (an optional) callback if major stuff is done:
- map creation
- parsed imports
- parsed layers
- parsed cameras
the callback will send both a string and a float (which shows
the overall process), callback(string, float)
@type engine: object
@param engine: FIFE engine instance
@type callback: function
@param callback: callback for maploading progress
@type debug: bool
@param debug: flag to activate / deactivate print statements
@rtype object
@return FIFE map object
"""
(filename, extension) = os.path.splitext(path)
map_loader = mapFileMapping[extension[1:]](engine, callback, debug, extensions)
map = map_loader.loadResource(path)
if debug: print("--- Loading map took: ", map_loader.time_to_load, " seconds.")
return map
def addMapLoader(fileExtension, loaderClass):
"""Add a new loader for fileextension
@type fileExtension: string
@param fileExtension: The file extension the loader is registered for
@type loaderClass: object
@param loaderClass: A fife.ResourceLoader implementation that loads maps
from files with the given fileExtension
"""
mapFileMapping[fileExtension] = loaderClass
_updateMapFileExtensions()
def _updateMapFileExtensions():
<|fim_middle|>
<|fim▁end|> | global fileExtensions
fileExtensions = set(mapFileMapping.keys()) |
<|file_name|>loaders.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# ####################################################################
# Copyright (C) 2005-2019 by the FIFE team
# http://www.fifengine.net
# This file is part of FIFE.
#
# FIFE is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
# ####################################################################
""" Loaders plugin manager """
from __future__ import print_function
import os.path
from fife import fife
from fife.extensions.serializers.xmlmap import XMLMapLoader
mapFileMapping = { 'xml' : XMLMapLoader}
fileExtensions = set(['xml'])
def loadMapFile(path, engine, callback=None, debug=True, extensions={}):
""" load map file and get (an optional) callback if major stuff is done:
- map creation
- parsed imports
- parsed layers
- parsed cameras
the callback will send both a string and a float (which shows
the overall process), callback(string, float)
@type engine: object
@param engine: FIFE engine instance
@type callback: function
@param callback: callback for maploading progress
@type debug: bool
@param debug: flag to activate / deactivate print statements
@rtype object
@return FIFE map object
"""
(filename, extension) = os.path.splitext(path)
map_loader = mapFileMapping[extension[1:]](engine, callback, debug, extensions)
map = map_loader.loadResource(path)
if debug: <|fim_middle|>
return map
def addMapLoader(fileExtension, loaderClass):
"""Add a new loader for fileextension
@type fileExtension: string
@param fileExtension: The file extension the loader is registered for
@type loaderClass: object
@param loaderClass: A fife.ResourceLoader implementation that loads maps
from files with the given fileExtension
"""
mapFileMapping[fileExtension] = loaderClass
_updateMapFileExtensions()
def _updateMapFileExtensions():
global fileExtensions
fileExtensions = set(mapFileMapping.keys())
<|fim▁end|> | print("--- Loading map took: ", map_loader.time_to_load, " seconds.") |
<|file_name|>loaders.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# ####################################################################
# Copyright (C) 2005-2019 by the FIFE team
# http://www.fifengine.net
# This file is part of FIFE.
#
# FIFE is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
# ####################################################################
""" Loaders plugin manager """
from __future__ import print_function
import os.path
from fife import fife
from fife.extensions.serializers.xmlmap import XMLMapLoader
mapFileMapping = { 'xml' : XMLMapLoader}
fileExtensions = set(['xml'])
def <|fim_middle|>(path, engine, callback=None, debug=True, extensions={}):
""" load map file and get (an optional) callback if major stuff is done:
- map creation
- parsed imports
- parsed layers
- parsed cameras
the callback will send both a string and a float (which shows
the overall process), callback(string, float)
@type engine: object
@param engine: FIFE engine instance
@type callback: function
@param callback: callback for maploading progress
@type debug: bool
@param debug: flag to activate / deactivate print statements
@rtype object
@return FIFE map object
"""
(filename, extension) = os.path.splitext(path)
map_loader = mapFileMapping[extension[1:]](engine, callback, debug, extensions)
map = map_loader.loadResource(path)
if debug: print("--- Loading map took: ", map_loader.time_to_load, " seconds.")
return map
def addMapLoader(fileExtension, loaderClass):
"""Add a new loader for fileextension
@type fileExtension: string
@param fileExtension: The file extension the loader is registered for
@type loaderClass: object
@param loaderClass: A fife.ResourceLoader implementation that loads maps
from files with the given fileExtension
"""
mapFileMapping[fileExtension] = loaderClass
_updateMapFileExtensions()
def _updateMapFileExtensions():
global fileExtensions
fileExtensions = set(mapFileMapping.keys())
<|fim▁end|> | loadMapFile |
<|file_name|>loaders.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# ####################################################################
# Copyright (C) 2005-2019 by the FIFE team
# http://www.fifengine.net
# This file is part of FIFE.
#
# FIFE is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
# ####################################################################
""" Loaders plugin manager """
from __future__ import print_function
import os.path
from fife import fife
from fife.extensions.serializers.xmlmap import XMLMapLoader
mapFileMapping = { 'xml' : XMLMapLoader}
fileExtensions = set(['xml'])
def loadMapFile(path, engine, callback=None, debug=True, extensions={}):
""" load map file and get (an optional) callback if major stuff is done:
- map creation
- parsed imports
- parsed layers
- parsed cameras
the callback will send both a string and a float (which shows
the overall process), callback(string, float)
@type engine: object
@param engine: FIFE engine instance
@type callback: function
@param callback: callback for maploading progress
@type debug: bool
@param debug: flag to activate / deactivate print statements
@rtype object
@return FIFE map object
"""
(filename, extension) = os.path.splitext(path)
map_loader = mapFileMapping[extension[1:]](engine, callback, debug, extensions)
map = map_loader.loadResource(path)
if debug: print("--- Loading map took: ", map_loader.time_to_load, " seconds.")
return map
def <|fim_middle|>(fileExtension, loaderClass):
"""Add a new loader for fileextension
@type fileExtension: string
@param fileExtension: The file extension the loader is registered for
@type loaderClass: object
@param loaderClass: A fife.ResourceLoader implementation that loads maps
from files with the given fileExtension
"""
mapFileMapping[fileExtension] = loaderClass
_updateMapFileExtensions()
def _updateMapFileExtensions():
global fileExtensions
fileExtensions = set(mapFileMapping.keys())
<|fim▁end|> | addMapLoader |
<|file_name|>loaders.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# ####################################################################
# Copyright (C) 2005-2019 by the FIFE team
# http://www.fifengine.net
# This file is part of FIFE.
#
# FIFE is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
# ####################################################################
""" Loaders plugin manager """
from __future__ import print_function
import os.path
from fife import fife
from fife.extensions.serializers.xmlmap import XMLMapLoader
mapFileMapping = { 'xml' : XMLMapLoader}
fileExtensions = set(['xml'])
def loadMapFile(path, engine, callback=None, debug=True, extensions={}):
""" load map file and get (an optional) callback if major stuff is done:
- map creation
- parsed imports
- parsed layers
- parsed cameras
the callback will send both a string and a float (which shows
the overall process), callback(string, float)
@type engine: object
@param engine: FIFE engine instance
@type callback: function
@param callback: callback for maploading progress
@type debug: bool
@param debug: flag to activate / deactivate print statements
@rtype object
@return FIFE map object
"""
(filename, extension) = os.path.splitext(path)
map_loader = mapFileMapping[extension[1:]](engine, callback, debug, extensions)
map = map_loader.loadResource(path)
if debug: print("--- Loading map took: ", map_loader.time_to_load, " seconds.")
return map
def addMapLoader(fileExtension, loaderClass):
"""Add a new loader for fileextension
@type fileExtension: string
@param fileExtension: The file extension the loader is registered for
@type loaderClass: object
@param loaderClass: A fife.ResourceLoader implementation that loads maps
from files with the given fileExtension
"""
mapFileMapping[fileExtension] = loaderClass
_updateMapFileExtensions()
def <|fim_middle|>():
global fileExtensions
fileExtensions = set(mapFileMapping.keys())
<|fim▁end|> | _updateMapFileExtensions |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># Copyright 2016 Mycroft AI, Inc.
#
# This file is part of Mycroft Core.
#
# Mycroft Core is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mycroft Core is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mycroft Core. If not, see <http://www.gnu.org/licenses/>.
from threading import Thread
from time import sleep
import random
from adapt.intent import IntentBuilder
from mycroft.messagebus.message import Message
from mycroft.skills.LILACS_core.question_parser import LILACSQuestionParser
from mycroft.skills.LILACS_knowledge.knowledgeservice import KnowledgeService
from mycroft.skills.core import MycroftSkill
from mycroft.util.log import getLogger
__author__ = 'jarbas'
logger = getLogger(__name__)
class LILACSChatbotSkill(MycroftSkill):
# https://github.com/ElliotTheRobot/LILACS-mycroft-core/issues/19
def __init__(self):
super(LILACSChatbotSkill, self).__init__(name="ChatbotSkill")
# initialize your variables
self.reload_skill = False
self.active = True
self.parser = None
self.service = None<|fim▁hole|>
def initialize(self):
# register intents
self.parser = LILACSQuestionParser()
self.service = KnowledgeService(self.emitter)
self.build_intents()
# make thread to keep active
self.make_bump_thread()
def ping(self):
while True:
i = 0
if self.active:
self.emitter.emit(Message("recognizer_loop:utterance", {"source": "LILACS_chatbot_skill",
"utterances": [
"bump chat to active skill list"]}))
while i < 60 * self.TIMEOUT:
i += 1
sleep(1)
i = 0
def make_bump_thread(self):
timer_thread = Thread(target=self.ping)
timer_thread.setDaemon(True)
timer_thread.start()
def build_intents(self):
# build intents
deactivate_intent = IntentBuilder("DeactivateChatbotIntent") \
.require("deactivateChatBotKeyword").build()
activate_intent=IntentBuilder("ActivateChatbotIntent") \
.require("activateChatBotKeyword").build()
bump_intent = IntentBuilder("BumpChatBotSkillIntent"). \
require("bumpChatBotKeyword").build()
# register intents
self.register_intent(deactivate_intent, self.handle_deactivate_intent)
self.register_intent(activate_intent, self.handle_activate_intent)
self.register_intent(bump_intent, self.handle_set_on_top_active_list())
def handle_set_on_top_active_list(self):
# dummy intent just to bump curiosity skill to top of active skill list
# called on a timer in order to always use converse method
pass
def handle_deactivate_intent(self, message):
self.active = False
self.speak_dialog("chatbot_off")
def handle_activate_intent(self, message):
self.active = True
self.speak_dialog("chatbot_on")
def stop(self):
self.handle_deactivate_intent("global stop")
def converse(self, transcript, lang="en-us"):
# parse 1st utterance for entitys
if self.active and "bump chat" not in transcript[0] and "bump curiosity" not in transcript[0]:
nodes, parents, synonims = self.parser.tag_from_dbpedia(transcript[0])
self.log.info("nodes: " + str(nodes))
self.log.info("parents: " + str(parents))
self.log.info("synonims: " + str(synonims))
# get concept net , talk
possible_responses = []
for node in nodes:
try:
dict = self.service.adquire(node, "concept net")
usages = dict["concept net"]["surfaceText"]
for usage in usages:
possible_responses.append(usage.replace("[", "").replace("]", ""))
except:
self.log.info("could not get reply for node " + node)
try:
# say something random
reply = random.choice(possible_responses)
self.speak(reply)
return True
except:
self.log.error("Could not get chatbot response for: " + transcript[0])
# dont know what to say
# TODO ask user a question and play du,mb
return False
# tell intent skill you did not handle intent
return False
def create_skill():
return LILACSChatbotSkill()<|fim▁end|> | self.TIMEOUT = 2 |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># Copyright 2016 Mycroft AI, Inc.
#
# This file is part of Mycroft Core.
#
# Mycroft Core is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mycroft Core is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mycroft Core. If not, see <http://www.gnu.org/licenses/>.
from threading import Thread
from time import sleep
import random
from adapt.intent import IntentBuilder
from mycroft.messagebus.message import Message
from mycroft.skills.LILACS_core.question_parser import LILACSQuestionParser
from mycroft.skills.LILACS_knowledge.knowledgeservice import KnowledgeService
from mycroft.skills.core import MycroftSkill
from mycroft.util.log import getLogger
__author__ = 'jarbas'
logger = getLogger(__name__)
class LILACSChatbotSkill(MycroftSkill):
# https://github.com/ElliotTheRobot/LILACS-mycroft-core/issues/19
<|fim_middle|>
def create_skill():
return LILACSChatbotSkill()<|fim▁end|> | def __init__(self):
super(LILACSChatbotSkill, self).__init__(name="ChatbotSkill")
# initialize your variables
self.reload_skill = False
self.active = True
self.parser = None
self.service = None
self.TIMEOUT = 2
def initialize(self):
# register intents
self.parser = LILACSQuestionParser()
self.service = KnowledgeService(self.emitter)
self.build_intents()
# make thread to keep active
self.make_bump_thread()
def ping(self):
while True:
i = 0
if self.active:
self.emitter.emit(Message("recognizer_loop:utterance", {"source": "LILACS_chatbot_skill",
"utterances": [
"bump chat to active skill list"]}))
while i < 60 * self.TIMEOUT:
i += 1
sleep(1)
i = 0
def make_bump_thread(self):
timer_thread = Thread(target=self.ping)
timer_thread.setDaemon(True)
timer_thread.start()
def build_intents(self):
# build intents
deactivate_intent = IntentBuilder("DeactivateChatbotIntent") \
.require("deactivateChatBotKeyword").build()
activate_intent=IntentBuilder("ActivateChatbotIntent") \
.require("activateChatBotKeyword").build()
bump_intent = IntentBuilder("BumpChatBotSkillIntent"). \
require("bumpChatBotKeyword").build()
# register intents
self.register_intent(deactivate_intent, self.handle_deactivate_intent)
self.register_intent(activate_intent, self.handle_activate_intent)
self.register_intent(bump_intent, self.handle_set_on_top_active_list())
def handle_set_on_top_active_list(self):
# dummy intent just to bump curiosity skill to top of active skill list
# called on a timer in order to always use converse method
pass
def handle_deactivate_intent(self, message):
self.active = False
self.speak_dialog("chatbot_off")
def handle_activate_intent(self, message):
self.active = True
self.speak_dialog("chatbot_on")
def stop(self):
self.handle_deactivate_intent("global stop")
def converse(self, transcript, lang="en-us"):
# parse 1st utterance for entitys
if self.active and "bump chat" not in transcript[0] and "bump curiosity" not in transcript[0]:
nodes, parents, synonims = self.parser.tag_from_dbpedia(transcript[0])
self.log.info("nodes: " + str(nodes))
self.log.info("parents: " + str(parents))
self.log.info("synonims: " + str(synonims))
# get concept net , talk
possible_responses = []
for node in nodes:
try:
dict = self.service.adquire(node, "concept net")
usages = dict["concept net"]["surfaceText"]
for usage in usages:
possible_responses.append(usage.replace("[", "").replace("]", ""))
except:
self.log.info("could not get reply for node " + node)
try:
# say something random
reply = random.choice(possible_responses)
self.speak(reply)
return True
except:
self.log.error("Could not get chatbot response for: " + transcript[0])
# dont know what to say
# TODO ask user a question and play du,mb
return False
# tell intent skill you did not handle intent
return False |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># Copyright 2016 Mycroft AI, Inc.
#
# This file is part of Mycroft Core.
#
# Mycroft Core is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mycroft Core is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mycroft Core. If not, see <http://www.gnu.org/licenses/>.
from threading import Thread
from time import sleep
import random
from adapt.intent import IntentBuilder
from mycroft.messagebus.message import Message
from mycroft.skills.LILACS_core.question_parser import LILACSQuestionParser
from mycroft.skills.LILACS_knowledge.knowledgeservice import KnowledgeService
from mycroft.skills.core import MycroftSkill
from mycroft.util.log import getLogger
__author__ = 'jarbas'
logger = getLogger(__name__)
class LILACSChatbotSkill(MycroftSkill):
# https://github.com/ElliotTheRobot/LILACS-mycroft-core/issues/19
def __init__(self):
<|fim_middle|>
def initialize(self):
# register intents
self.parser = LILACSQuestionParser()
self.service = KnowledgeService(self.emitter)
self.build_intents()
# make thread to keep active
self.make_bump_thread()
def ping(self):
while True:
i = 0
if self.active:
self.emitter.emit(Message("recognizer_loop:utterance", {"source": "LILACS_chatbot_skill",
"utterances": [
"bump chat to active skill list"]}))
while i < 60 * self.TIMEOUT:
i += 1
sleep(1)
i = 0
def make_bump_thread(self):
timer_thread = Thread(target=self.ping)
timer_thread.setDaemon(True)
timer_thread.start()
def build_intents(self):
# build intents
deactivate_intent = IntentBuilder("DeactivateChatbotIntent") \
.require("deactivateChatBotKeyword").build()
activate_intent=IntentBuilder("ActivateChatbotIntent") \
.require("activateChatBotKeyword").build()
bump_intent = IntentBuilder("BumpChatBotSkillIntent"). \
require("bumpChatBotKeyword").build()
# register intents
self.register_intent(deactivate_intent, self.handle_deactivate_intent)
self.register_intent(activate_intent, self.handle_activate_intent)
self.register_intent(bump_intent, self.handle_set_on_top_active_list())
def handle_set_on_top_active_list(self):
# dummy intent just to bump curiosity skill to top of active skill list
# called on a timer in order to always use converse method
pass
def handle_deactivate_intent(self, message):
self.active = False
self.speak_dialog("chatbot_off")
def handle_activate_intent(self, message):
self.active = True
self.speak_dialog("chatbot_on")
def stop(self):
self.handle_deactivate_intent("global stop")
def converse(self, transcript, lang="en-us"):
# parse 1st utterance for entitys
if self.active and "bump chat" not in transcript[0] and "bump curiosity" not in transcript[0]:
nodes, parents, synonims = self.parser.tag_from_dbpedia(transcript[0])
self.log.info("nodes: " + str(nodes))
self.log.info("parents: " + str(parents))
self.log.info("synonims: " + str(synonims))
# get concept net , talk
possible_responses = []
for node in nodes:
try:
dict = self.service.adquire(node, "concept net")
usages = dict["concept net"]["surfaceText"]
for usage in usages:
possible_responses.append(usage.replace("[", "").replace("]", ""))
except:
self.log.info("could not get reply for node " + node)
try:
# say something random
reply = random.choice(possible_responses)
self.speak(reply)
return True
except:
self.log.error("Could not get chatbot response for: " + transcript[0])
# dont know what to say
# TODO ask user a question and play du,mb
return False
# tell intent skill you did not handle intent
return False
def create_skill():
return LILACSChatbotSkill()<|fim▁end|> | super(LILACSChatbotSkill, self).__init__(name="ChatbotSkill")
# initialize your variables
self.reload_skill = False
self.active = True
self.parser = None
self.service = None
self.TIMEOUT = 2 |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># Copyright 2016 Mycroft AI, Inc.
#
# This file is part of Mycroft Core.
#
# Mycroft Core is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mycroft Core is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mycroft Core. If not, see <http://www.gnu.org/licenses/>.
from threading import Thread
from time import sleep
import random
from adapt.intent import IntentBuilder
from mycroft.messagebus.message import Message
from mycroft.skills.LILACS_core.question_parser import LILACSQuestionParser
from mycroft.skills.LILACS_knowledge.knowledgeservice import KnowledgeService
from mycroft.skills.core import MycroftSkill
from mycroft.util.log import getLogger
__author__ = 'jarbas'
logger = getLogger(__name__)
class LILACSChatbotSkill(MycroftSkill):
# https://github.com/ElliotTheRobot/LILACS-mycroft-core/issues/19
def __init__(self):
super(LILACSChatbotSkill, self).__init__(name="ChatbotSkill")
# initialize your variables
self.reload_skill = False
self.active = True
self.parser = None
self.service = None
self.TIMEOUT = 2
def initialize(self):
# register intents
<|fim_middle|>
def ping(self):
while True:
i = 0
if self.active:
self.emitter.emit(Message("recognizer_loop:utterance", {"source": "LILACS_chatbot_skill",
"utterances": [
"bump chat to active skill list"]}))
while i < 60 * self.TIMEOUT:
i += 1
sleep(1)
i = 0
def make_bump_thread(self):
timer_thread = Thread(target=self.ping)
timer_thread.setDaemon(True)
timer_thread.start()
def build_intents(self):
# build intents
deactivate_intent = IntentBuilder("DeactivateChatbotIntent") \
.require("deactivateChatBotKeyword").build()
activate_intent=IntentBuilder("ActivateChatbotIntent") \
.require("activateChatBotKeyword").build()
bump_intent = IntentBuilder("BumpChatBotSkillIntent"). \
require("bumpChatBotKeyword").build()
# register intents
self.register_intent(deactivate_intent, self.handle_deactivate_intent)
self.register_intent(activate_intent, self.handle_activate_intent)
self.register_intent(bump_intent, self.handle_set_on_top_active_list())
def handle_set_on_top_active_list(self):
# dummy intent just to bump curiosity skill to top of active skill list
# called on a timer in order to always use converse method
pass
def handle_deactivate_intent(self, message):
self.active = False
self.speak_dialog("chatbot_off")
def handle_activate_intent(self, message):
self.active = True
self.speak_dialog("chatbot_on")
def stop(self):
self.handle_deactivate_intent("global stop")
def converse(self, transcript, lang="en-us"):
# parse 1st utterance for entitys
if self.active and "bump chat" not in transcript[0] and "bump curiosity" not in transcript[0]:
nodes, parents, synonims = self.parser.tag_from_dbpedia(transcript[0])
self.log.info("nodes: " + str(nodes))
self.log.info("parents: " + str(parents))
self.log.info("synonims: " + str(synonims))
# get concept net , talk
possible_responses = []
for node in nodes:
try:
dict = self.service.adquire(node, "concept net")
usages = dict["concept net"]["surfaceText"]
for usage in usages:
possible_responses.append(usage.replace("[", "").replace("]", ""))
except:
self.log.info("could not get reply for node " + node)
try:
# say something random
reply = random.choice(possible_responses)
self.speak(reply)
return True
except:
self.log.error("Could not get chatbot response for: " + transcript[0])
# dont know what to say
# TODO ask user a question and play du,mb
return False
# tell intent skill you did not handle intent
return False
def create_skill():
return LILACSChatbotSkill()<|fim▁end|> | self.parser = LILACSQuestionParser()
self.service = KnowledgeService(self.emitter)
self.build_intents()
# make thread to keep active
self.make_bump_thread() |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># Copyright 2016 Mycroft AI, Inc.
#
# This file is part of Mycroft Core.
#
# Mycroft Core is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mycroft Core is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mycroft Core. If not, see <http://www.gnu.org/licenses/>.
from threading import Thread
from time import sleep
import random
from adapt.intent import IntentBuilder
from mycroft.messagebus.message import Message
from mycroft.skills.LILACS_core.question_parser import LILACSQuestionParser
from mycroft.skills.LILACS_knowledge.knowledgeservice import KnowledgeService
from mycroft.skills.core import MycroftSkill
from mycroft.util.log import getLogger
__author__ = 'jarbas'
logger = getLogger(__name__)
class LILACSChatbotSkill(MycroftSkill):
# https://github.com/ElliotTheRobot/LILACS-mycroft-core/issues/19
def __init__(self):
super(LILACSChatbotSkill, self).__init__(name="ChatbotSkill")
# initialize your variables
self.reload_skill = False
self.active = True
self.parser = None
self.service = None
self.TIMEOUT = 2
def initialize(self):
# register intents
self.parser = LILACSQuestionParser()
self.service = KnowledgeService(self.emitter)
self.build_intents()
# make thread to keep active
self.make_bump_thread()
def ping(self):
<|fim_middle|>
def make_bump_thread(self):
timer_thread = Thread(target=self.ping)
timer_thread.setDaemon(True)
timer_thread.start()
def build_intents(self):
# build intents
deactivate_intent = IntentBuilder("DeactivateChatbotIntent") \
.require("deactivateChatBotKeyword").build()
activate_intent=IntentBuilder("ActivateChatbotIntent") \
.require("activateChatBotKeyword").build()
bump_intent = IntentBuilder("BumpChatBotSkillIntent"). \
require("bumpChatBotKeyword").build()
# register intents
self.register_intent(deactivate_intent, self.handle_deactivate_intent)
self.register_intent(activate_intent, self.handle_activate_intent)
self.register_intent(bump_intent, self.handle_set_on_top_active_list())
def handle_set_on_top_active_list(self):
# dummy intent just to bump curiosity skill to top of active skill list
# called on a timer in order to always use converse method
pass
def handle_deactivate_intent(self, message):
self.active = False
self.speak_dialog("chatbot_off")
def handle_activate_intent(self, message):
self.active = True
self.speak_dialog("chatbot_on")
def stop(self):
self.handle_deactivate_intent("global stop")
def converse(self, transcript, lang="en-us"):
# parse 1st utterance for entitys
if self.active and "bump chat" not in transcript[0] and "bump curiosity" not in transcript[0]:
nodes, parents, synonims = self.parser.tag_from_dbpedia(transcript[0])
self.log.info("nodes: " + str(nodes))
self.log.info("parents: " + str(parents))
self.log.info("synonims: " + str(synonims))
# get concept net , talk
possible_responses = []
for node in nodes:
try:
dict = self.service.adquire(node, "concept net")
usages = dict["concept net"]["surfaceText"]
for usage in usages:
possible_responses.append(usage.replace("[", "").replace("]", ""))
except:
self.log.info("could not get reply for node " + node)
try:
# say something random
reply = random.choice(possible_responses)
self.speak(reply)
return True
except:
self.log.error("Could not get chatbot response for: " + transcript[0])
# dont know what to say
# TODO ask user a question and play du,mb
return False
# tell intent skill you did not handle intent
return False
def create_skill():
return LILACSChatbotSkill()<|fim▁end|> | while True:
i = 0
if self.active:
self.emitter.emit(Message("recognizer_loop:utterance", {"source": "LILACS_chatbot_skill",
"utterances": [
"bump chat to active skill list"]}))
while i < 60 * self.TIMEOUT:
i += 1
sleep(1)
i = 0 |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># Copyright 2016 Mycroft AI, Inc.
#
# This file is part of Mycroft Core.
#
# Mycroft Core is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mycroft Core is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mycroft Core. If not, see <http://www.gnu.org/licenses/>.
from threading import Thread
from time import sleep
import random
from adapt.intent import IntentBuilder
from mycroft.messagebus.message import Message
from mycroft.skills.LILACS_core.question_parser import LILACSQuestionParser
from mycroft.skills.LILACS_knowledge.knowledgeservice import KnowledgeService
from mycroft.skills.core import MycroftSkill
from mycroft.util.log import getLogger
__author__ = 'jarbas'
logger = getLogger(__name__)
class LILACSChatbotSkill(MycroftSkill):
# https://github.com/ElliotTheRobot/LILACS-mycroft-core/issues/19
def __init__(self):
super(LILACSChatbotSkill, self).__init__(name="ChatbotSkill")
# initialize your variables
self.reload_skill = False
self.active = True
self.parser = None
self.service = None
self.TIMEOUT = 2
def initialize(self):
# register intents
self.parser = LILACSQuestionParser()
self.service = KnowledgeService(self.emitter)
self.build_intents()
# make thread to keep active
self.make_bump_thread()
def ping(self):
while True:
i = 0
if self.active:
self.emitter.emit(Message("recognizer_loop:utterance", {"source": "LILACS_chatbot_skill",
"utterances": [
"bump chat to active skill list"]}))
while i < 60 * self.TIMEOUT:
i += 1
sleep(1)
i = 0
def make_bump_thread(self):
<|fim_middle|>
def build_intents(self):
# build intents
deactivate_intent = IntentBuilder("DeactivateChatbotIntent") \
.require("deactivateChatBotKeyword").build()
activate_intent=IntentBuilder("ActivateChatbotIntent") \
.require("activateChatBotKeyword").build()
bump_intent = IntentBuilder("BumpChatBotSkillIntent"). \
require("bumpChatBotKeyword").build()
# register intents
self.register_intent(deactivate_intent, self.handle_deactivate_intent)
self.register_intent(activate_intent, self.handle_activate_intent)
self.register_intent(bump_intent, self.handle_set_on_top_active_list())
def handle_set_on_top_active_list(self):
# dummy intent just to bump curiosity skill to top of active skill list
# called on a timer in order to always use converse method
pass
def handle_deactivate_intent(self, message):
self.active = False
self.speak_dialog("chatbot_off")
def handle_activate_intent(self, message):
self.active = True
self.speak_dialog("chatbot_on")
def stop(self):
self.handle_deactivate_intent("global stop")
def converse(self, transcript, lang="en-us"):
# parse 1st utterance for entitys
if self.active and "bump chat" not in transcript[0] and "bump curiosity" not in transcript[0]:
nodes, parents, synonims = self.parser.tag_from_dbpedia(transcript[0])
self.log.info("nodes: " + str(nodes))
self.log.info("parents: " + str(parents))
self.log.info("synonims: " + str(synonims))
# get concept net , talk
possible_responses = []
for node in nodes:
try:
dict = self.service.adquire(node, "concept net")
usages = dict["concept net"]["surfaceText"]
for usage in usages:
possible_responses.append(usage.replace("[", "").replace("]", ""))
except:
self.log.info("could not get reply for node " + node)
try:
# say something random
reply = random.choice(possible_responses)
self.speak(reply)
return True
except:
self.log.error("Could not get chatbot response for: " + transcript[0])
# dont know what to say
# TODO ask user a question and play du,mb
return False
# tell intent skill you did not handle intent
return False
def create_skill():
return LILACSChatbotSkill()<|fim▁end|> | timer_thread = Thread(target=self.ping)
timer_thread.setDaemon(True)
timer_thread.start() |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># Copyright 2016 Mycroft AI, Inc.
#
# This file is part of Mycroft Core.
#
# Mycroft Core is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mycroft Core is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mycroft Core. If not, see <http://www.gnu.org/licenses/>.
from threading import Thread
from time import sleep
import random
from adapt.intent import IntentBuilder
from mycroft.messagebus.message import Message
from mycroft.skills.LILACS_core.question_parser import LILACSQuestionParser
from mycroft.skills.LILACS_knowledge.knowledgeservice import KnowledgeService
from mycroft.skills.core import MycroftSkill
from mycroft.util.log import getLogger
__author__ = 'jarbas'
logger = getLogger(__name__)
class LILACSChatbotSkill(MycroftSkill):
# https://github.com/ElliotTheRobot/LILACS-mycroft-core/issues/19
def __init__(self):
super(LILACSChatbotSkill, self).__init__(name="ChatbotSkill")
# initialize your variables
self.reload_skill = False
self.active = True
self.parser = None
self.service = None
self.TIMEOUT = 2
def initialize(self):
# register intents
self.parser = LILACSQuestionParser()
self.service = KnowledgeService(self.emitter)
self.build_intents()
# make thread to keep active
self.make_bump_thread()
def ping(self):
while True:
i = 0
if self.active:
self.emitter.emit(Message("recognizer_loop:utterance", {"source": "LILACS_chatbot_skill",
"utterances": [
"bump chat to active skill list"]}))
while i < 60 * self.TIMEOUT:
i += 1
sleep(1)
i = 0
def make_bump_thread(self):
timer_thread = Thread(target=self.ping)
timer_thread.setDaemon(True)
timer_thread.start()
def build_intents(self):
# build intents
<|fim_middle|>
def handle_set_on_top_active_list(self):
# dummy intent just to bump curiosity skill to top of active skill list
# called on a timer in order to always use converse method
pass
def handle_deactivate_intent(self, message):
self.active = False
self.speak_dialog("chatbot_off")
def handle_activate_intent(self, message):
self.active = True
self.speak_dialog("chatbot_on")
def stop(self):
self.handle_deactivate_intent("global stop")
def converse(self, transcript, lang="en-us"):
# parse 1st utterance for entitys
if self.active and "bump chat" not in transcript[0] and "bump curiosity" not in transcript[0]:
nodes, parents, synonims = self.parser.tag_from_dbpedia(transcript[0])
self.log.info("nodes: " + str(nodes))
self.log.info("parents: " + str(parents))
self.log.info("synonims: " + str(synonims))
# get concept net , talk
possible_responses = []
for node in nodes:
try:
dict = self.service.adquire(node, "concept net")
usages = dict["concept net"]["surfaceText"]
for usage in usages:
possible_responses.append(usage.replace("[", "").replace("]", ""))
except:
self.log.info("could not get reply for node " + node)
try:
# say something random
reply = random.choice(possible_responses)
self.speak(reply)
return True
except:
self.log.error("Could not get chatbot response for: " + transcript[0])
# dont know what to say
# TODO ask user a question and play du,mb
return False
# tell intent skill you did not handle intent
return False
def create_skill():
return LILACSChatbotSkill()<|fim▁end|> | deactivate_intent = IntentBuilder("DeactivateChatbotIntent") \
.require("deactivateChatBotKeyword").build()
activate_intent=IntentBuilder("ActivateChatbotIntent") \
.require("activateChatBotKeyword").build()
bump_intent = IntentBuilder("BumpChatBotSkillIntent"). \
require("bumpChatBotKeyword").build()
# register intents
self.register_intent(deactivate_intent, self.handle_deactivate_intent)
self.register_intent(activate_intent, self.handle_activate_intent)
self.register_intent(bump_intent, self.handle_set_on_top_active_list()) |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># Copyright 2016 Mycroft AI, Inc.
#
# This file is part of Mycroft Core.
#
# Mycroft Core is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mycroft Core is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mycroft Core. If not, see <http://www.gnu.org/licenses/>.
from threading import Thread
from time import sleep
import random
from adapt.intent import IntentBuilder
from mycroft.messagebus.message import Message
from mycroft.skills.LILACS_core.question_parser import LILACSQuestionParser
from mycroft.skills.LILACS_knowledge.knowledgeservice import KnowledgeService
from mycroft.skills.core import MycroftSkill
from mycroft.util.log import getLogger
__author__ = 'jarbas'
logger = getLogger(__name__)
class LILACSChatbotSkill(MycroftSkill):
# https://github.com/ElliotTheRobot/LILACS-mycroft-core/issues/19
def __init__(self):
super(LILACSChatbotSkill, self).__init__(name="ChatbotSkill")
# initialize your variables
self.reload_skill = False
self.active = True
self.parser = None
self.service = None
self.TIMEOUT = 2
def initialize(self):
# register intents
self.parser = LILACSQuestionParser()
self.service = KnowledgeService(self.emitter)
self.build_intents()
# make thread to keep active
self.make_bump_thread()
def ping(self):
while True:
i = 0
if self.active:
self.emitter.emit(Message("recognizer_loop:utterance", {"source": "LILACS_chatbot_skill",
"utterances": [
"bump chat to active skill list"]}))
while i < 60 * self.TIMEOUT:
i += 1
sleep(1)
i = 0
def make_bump_thread(self):
timer_thread = Thread(target=self.ping)
timer_thread.setDaemon(True)
timer_thread.start()
def build_intents(self):
# build intents
deactivate_intent = IntentBuilder("DeactivateChatbotIntent") \
.require("deactivateChatBotKeyword").build()
activate_intent=IntentBuilder("ActivateChatbotIntent") \
.require("activateChatBotKeyword").build()
bump_intent = IntentBuilder("BumpChatBotSkillIntent"). \
require("bumpChatBotKeyword").build()
# register intents
self.register_intent(deactivate_intent, self.handle_deactivate_intent)
self.register_intent(activate_intent, self.handle_activate_intent)
self.register_intent(bump_intent, self.handle_set_on_top_active_list())
def handle_set_on_top_active_list(self):
# dummy intent just to bump curiosity skill to top of active skill list
# called on a timer in order to always use converse method
<|fim_middle|>
def handle_deactivate_intent(self, message):
self.active = False
self.speak_dialog("chatbot_off")
def handle_activate_intent(self, message):
self.active = True
self.speak_dialog("chatbot_on")
def stop(self):
self.handle_deactivate_intent("global stop")
def converse(self, transcript, lang="en-us"):
# parse 1st utterance for entitys
if self.active and "bump chat" not in transcript[0] and "bump curiosity" not in transcript[0]:
nodes, parents, synonims = self.parser.tag_from_dbpedia(transcript[0])
self.log.info("nodes: " + str(nodes))
self.log.info("parents: " + str(parents))
self.log.info("synonims: " + str(synonims))
# get concept net , talk
possible_responses = []
for node in nodes:
try:
dict = self.service.adquire(node, "concept net")
usages = dict["concept net"]["surfaceText"]
for usage in usages:
possible_responses.append(usage.replace("[", "").replace("]", ""))
except:
self.log.info("could not get reply for node " + node)
try:
# say something random
reply = random.choice(possible_responses)
self.speak(reply)
return True
except:
self.log.error("Could not get chatbot response for: " + transcript[0])
# dont know what to say
# TODO ask user a question and play du,mb
return False
# tell intent skill you did not handle intent
return False
def create_skill():
return LILACSChatbotSkill()<|fim▁end|> | pass |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># Copyright 2016 Mycroft AI, Inc.
#
# This file is part of Mycroft Core.
#
# Mycroft Core is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mycroft Core is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mycroft Core. If not, see <http://www.gnu.org/licenses/>.
from threading import Thread
from time import sleep
import random
from adapt.intent import IntentBuilder
from mycroft.messagebus.message import Message
from mycroft.skills.LILACS_core.question_parser import LILACSQuestionParser
from mycroft.skills.LILACS_knowledge.knowledgeservice import KnowledgeService
from mycroft.skills.core import MycroftSkill
from mycroft.util.log import getLogger
__author__ = 'jarbas'
logger = getLogger(__name__)
class LILACSChatbotSkill(MycroftSkill):
# https://github.com/ElliotTheRobot/LILACS-mycroft-core/issues/19
def __init__(self):
super(LILACSChatbotSkill, self).__init__(name="ChatbotSkill")
# initialize your variables
self.reload_skill = False
self.active = True
self.parser = None
self.service = None
self.TIMEOUT = 2
def initialize(self):
# register intents
self.parser = LILACSQuestionParser()
self.service = KnowledgeService(self.emitter)
self.build_intents()
# make thread to keep active
self.make_bump_thread()
def ping(self):
while True:
i = 0
if self.active:
self.emitter.emit(Message("recognizer_loop:utterance", {"source": "LILACS_chatbot_skill",
"utterances": [
"bump chat to active skill list"]}))
while i < 60 * self.TIMEOUT:
i += 1
sleep(1)
i = 0
def make_bump_thread(self):
timer_thread = Thread(target=self.ping)
timer_thread.setDaemon(True)
timer_thread.start()
def build_intents(self):
# build intents
deactivate_intent = IntentBuilder("DeactivateChatbotIntent") \
.require("deactivateChatBotKeyword").build()
activate_intent=IntentBuilder("ActivateChatbotIntent") \
.require("activateChatBotKeyword").build()
bump_intent = IntentBuilder("BumpChatBotSkillIntent"). \
require("bumpChatBotKeyword").build()
# register intents
self.register_intent(deactivate_intent, self.handle_deactivate_intent)
self.register_intent(activate_intent, self.handle_activate_intent)
self.register_intent(bump_intent, self.handle_set_on_top_active_list())
def handle_set_on_top_active_list(self):
# dummy intent just to bump curiosity skill to top of active skill list
# called on a timer in order to always use converse method
pass
def handle_deactivate_intent(self, message):
<|fim_middle|>
def handle_activate_intent(self, message):
self.active = True
self.speak_dialog("chatbot_on")
def stop(self):
self.handle_deactivate_intent("global stop")
def converse(self, transcript, lang="en-us"):
# parse 1st utterance for entitys
if self.active and "bump chat" not in transcript[0] and "bump curiosity" not in transcript[0]:
nodes, parents, synonims = self.parser.tag_from_dbpedia(transcript[0])
self.log.info("nodes: " + str(nodes))
self.log.info("parents: " + str(parents))
self.log.info("synonims: " + str(synonims))
# get concept net , talk
possible_responses = []
for node in nodes:
try:
dict = self.service.adquire(node, "concept net")
usages = dict["concept net"]["surfaceText"]
for usage in usages:
possible_responses.append(usage.replace("[", "").replace("]", ""))
except:
self.log.info("could not get reply for node " + node)
try:
# say something random
reply = random.choice(possible_responses)
self.speak(reply)
return True
except:
self.log.error("Could not get chatbot response for: " + transcript[0])
# dont know what to say
# TODO ask user a question and play du,mb
return False
# tell intent skill you did not handle intent
return False
def create_skill():
return LILACSChatbotSkill()<|fim▁end|> | self.active = False
self.speak_dialog("chatbot_off") |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># Copyright 2016 Mycroft AI, Inc.
#
# This file is part of Mycroft Core.
#
# Mycroft Core is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mycroft Core is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mycroft Core. If not, see <http://www.gnu.org/licenses/>.
from threading import Thread
from time import sleep
import random
from adapt.intent import IntentBuilder
from mycroft.messagebus.message import Message
from mycroft.skills.LILACS_core.question_parser import LILACSQuestionParser
from mycroft.skills.LILACS_knowledge.knowledgeservice import KnowledgeService
from mycroft.skills.core import MycroftSkill
from mycroft.util.log import getLogger
__author__ = 'jarbas'
logger = getLogger(__name__)
class LILACSChatbotSkill(MycroftSkill):
# https://github.com/ElliotTheRobot/LILACS-mycroft-core/issues/19
def __init__(self):
super(LILACSChatbotSkill, self).__init__(name="ChatbotSkill")
# initialize your variables
self.reload_skill = False
self.active = True
self.parser = None
self.service = None
self.TIMEOUT = 2
def initialize(self):
# register intents
self.parser = LILACSQuestionParser()
self.service = KnowledgeService(self.emitter)
self.build_intents()
# make thread to keep active
self.make_bump_thread()
def ping(self):
while True:
i = 0
if self.active:
self.emitter.emit(Message("recognizer_loop:utterance", {"source": "LILACS_chatbot_skill",
"utterances": [
"bump chat to active skill list"]}))
while i < 60 * self.TIMEOUT:
i += 1
sleep(1)
i = 0
def make_bump_thread(self):
timer_thread = Thread(target=self.ping)
timer_thread.setDaemon(True)
timer_thread.start()
def build_intents(self):
# build intents
deactivate_intent = IntentBuilder("DeactivateChatbotIntent") \
.require("deactivateChatBotKeyword").build()
activate_intent=IntentBuilder("ActivateChatbotIntent") \
.require("activateChatBotKeyword").build()
bump_intent = IntentBuilder("BumpChatBotSkillIntent"). \
require("bumpChatBotKeyword").build()
# register intents
self.register_intent(deactivate_intent, self.handle_deactivate_intent)
self.register_intent(activate_intent, self.handle_activate_intent)
self.register_intent(bump_intent, self.handle_set_on_top_active_list())
def handle_set_on_top_active_list(self):
# dummy intent just to bump curiosity skill to top of active skill list
# called on a timer in order to always use converse method
pass
def handle_deactivate_intent(self, message):
self.active = False
self.speak_dialog("chatbot_off")
def handle_activate_intent(self, message):
<|fim_middle|>
def stop(self):
self.handle_deactivate_intent("global stop")
def converse(self, transcript, lang="en-us"):
# parse 1st utterance for entitys
if self.active and "bump chat" not in transcript[0] and "bump curiosity" not in transcript[0]:
nodes, parents, synonims = self.parser.tag_from_dbpedia(transcript[0])
self.log.info("nodes: " + str(nodes))
self.log.info("parents: " + str(parents))
self.log.info("synonims: " + str(synonims))
# get concept net , talk
possible_responses = []
for node in nodes:
try:
dict = self.service.adquire(node, "concept net")
usages = dict["concept net"]["surfaceText"]
for usage in usages:
possible_responses.append(usage.replace("[", "").replace("]", ""))
except:
self.log.info("could not get reply for node " + node)
try:
# say something random
reply = random.choice(possible_responses)
self.speak(reply)
return True
except:
self.log.error("Could not get chatbot response for: " + transcript[0])
# dont know what to say
# TODO ask user a question and play du,mb
return False
# tell intent skill you did not handle intent
return False
def create_skill():
return LILACSChatbotSkill()<|fim▁end|> | self.active = True
self.speak_dialog("chatbot_on") |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># Copyright 2016 Mycroft AI, Inc.
#
# This file is part of Mycroft Core.
#
# Mycroft Core is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mycroft Core is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mycroft Core. If not, see <http://www.gnu.org/licenses/>.
from threading import Thread
from time import sleep
import random
from adapt.intent import IntentBuilder
from mycroft.messagebus.message import Message
from mycroft.skills.LILACS_core.question_parser import LILACSQuestionParser
from mycroft.skills.LILACS_knowledge.knowledgeservice import KnowledgeService
from mycroft.skills.core import MycroftSkill
from mycroft.util.log import getLogger
__author__ = 'jarbas'
logger = getLogger(__name__)
class LILACSChatbotSkill(MycroftSkill):
# https://github.com/ElliotTheRobot/LILACS-mycroft-core/issues/19
def __init__(self):
super(LILACSChatbotSkill, self).__init__(name="ChatbotSkill")
# initialize your variables
self.reload_skill = False
self.active = True
self.parser = None
self.service = None
self.TIMEOUT = 2
def initialize(self):
# register intents
self.parser = LILACSQuestionParser()
self.service = KnowledgeService(self.emitter)
self.build_intents()
# make thread to keep active
self.make_bump_thread()
def ping(self):
while True:
i = 0
if self.active:
self.emitter.emit(Message("recognizer_loop:utterance", {"source": "LILACS_chatbot_skill",
"utterances": [
"bump chat to active skill list"]}))
while i < 60 * self.TIMEOUT:
i += 1
sleep(1)
i = 0
def make_bump_thread(self):
timer_thread = Thread(target=self.ping)
timer_thread.setDaemon(True)
timer_thread.start()
def build_intents(self):
# build intents
deactivate_intent = IntentBuilder("DeactivateChatbotIntent") \
.require("deactivateChatBotKeyword").build()
activate_intent=IntentBuilder("ActivateChatbotIntent") \
.require("activateChatBotKeyword").build()
bump_intent = IntentBuilder("BumpChatBotSkillIntent"). \
require("bumpChatBotKeyword").build()
# register intents
self.register_intent(deactivate_intent, self.handle_deactivate_intent)
self.register_intent(activate_intent, self.handle_activate_intent)
self.register_intent(bump_intent, self.handle_set_on_top_active_list())
def handle_set_on_top_active_list(self):
# dummy intent just to bump curiosity skill to top of active skill list
# called on a timer in order to always use converse method
pass
def handle_deactivate_intent(self, message):
self.active = False
self.speak_dialog("chatbot_off")
def handle_activate_intent(self, message):
self.active = True
self.speak_dialog("chatbot_on")
def stop(self):
<|fim_middle|>
def converse(self, transcript, lang="en-us"):
# parse 1st utterance for entitys
if self.active and "bump chat" not in transcript[0] and "bump curiosity" not in transcript[0]:
nodes, parents, synonims = self.parser.tag_from_dbpedia(transcript[0])
self.log.info("nodes: " + str(nodes))
self.log.info("parents: " + str(parents))
self.log.info("synonims: " + str(synonims))
# get concept net , talk
possible_responses = []
for node in nodes:
try:
dict = self.service.adquire(node, "concept net")
usages = dict["concept net"]["surfaceText"]
for usage in usages:
possible_responses.append(usage.replace("[", "").replace("]", ""))
except:
self.log.info("could not get reply for node " + node)
try:
# say something random
reply = random.choice(possible_responses)
self.speak(reply)
return True
except:
self.log.error("Could not get chatbot response for: " + transcript[0])
# dont know what to say
# TODO ask user a question and play du,mb
return False
# tell intent skill you did not handle intent
return False
def create_skill():
return LILACSChatbotSkill()<|fim▁end|> | self.handle_deactivate_intent("global stop") |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># Copyright 2016 Mycroft AI, Inc.
#
# This file is part of Mycroft Core.
#
# Mycroft Core is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mycroft Core is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mycroft Core. If not, see <http://www.gnu.org/licenses/>.
from threading import Thread
from time import sleep
import random
from adapt.intent import IntentBuilder
from mycroft.messagebus.message import Message
from mycroft.skills.LILACS_core.question_parser import LILACSQuestionParser
from mycroft.skills.LILACS_knowledge.knowledgeservice import KnowledgeService
from mycroft.skills.core import MycroftSkill
from mycroft.util.log import getLogger
__author__ = 'jarbas'
logger = getLogger(__name__)
class LILACSChatbotSkill(MycroftSkill):
# https://github.com/ElliotTheRobot/LILACS-mycroft-core/issues/19
def __init__(self):
super(LILACSChatbotSkill, self).__init__(name="ChatbotSkill")
# initialize your variables
self.reload_skill = False
self.active = True
self.parser = None
self.service = None
self.TIMEOUT = 2
def initialize(self):
# register intents
self.parser = LILACSQuestionParser()
self.service = KnowledgeService(self.emitter)
self.build_intents()
# make thread to keep active
self.make_bump_thread()
def ping(self):
while True:
i = 0
if self.active:
self.emitter.emit(Message("recognizer_loop:utterance", {"source": "LILACS_chatbot_skill",
"utterances": [
"bump chat to active skill list"]}))
while i < 60 * self.TIMEOUT:
i += 1
sleep(1)
i = 0
def make_bump_thread(self):
timer_thread = Thread(target=self.ping)
timer_thread.setDaemon(True)
timer_thread.start()
def build_intents(self):
# build intents
deactivate_intent = IntentBuilder("DeactivateChatbotIntent") \
.require("deactivateChatBotKeyword").build()
activate_intent=IntentBuilder("ActivateChatbotIntent") \
.require("activateChatBotKeyword").build()
bump_intent = IntentBuilder("BumpChatBotSkillIntent"). \
require("bumpChatBotKeyword").build()
# register intents
self.register_intent(deactivate_intent, self.handle_deactivate_intent)
self.register_intent(activate_intent, self.handle_activate_intent)
self.register_intent(bump_intent, self.handle_set_on_top_active_list())
def handle_set_on_top_active_list(self):
# dummy intent just to bump curiosity skill to top of active skill list
# called on a timer in order to always use converse method
pass
def handle_deactivate_intent(self, message):
self.active = False
self.speak_dialog("chatbot_off")
def handle_activate_intent(self, message):
self.active = True
self.speak_dialog("chatbot_on")
def stop(self):
self.handle_deactivate_intent("global stop")
def converse(self, transcript, lang="en-us"):
# parse 1st utterance for entitys
<|fim_middle|>
def create_skill():
return LILACSChatbotSkill()<|fim▁end|> | if self.active and "bump chat" not in transcript[0] and "bump curiosity" not in transcript[0]:
nodes, parents, synonims = self.parser.tag_from_dbpedia(transcript[0])
self.log.info("nodes: " + str(nodes))
self.log.info("parents: " + str(parents))
self.log.info("synonims: " + str(synonims))
# get concept net , talk
possible_responses = []
for node in nodes:
try:
dict = self.service.adquire(node, "concept net")
usages = dict["concept net"]["surfaceText"]
for usage in usages:
possible_responses.append(usage.replace("[", "").replace("]", ""))
except:
self.log.info("could not get reply for node " + node)
try:
# say something random
reply = random.choice(possible_responses)
self.speak(reply)
return True
except:
self.log.error("Could not get chatbot response for: " + transcript[0])
# dont know what to say
# TODO ask user a question and play du,mb
return False
# tell intent skill you did not handle intent
return False |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># Copyright 2016 Mycroft AI, Inc.
#
# This file is part of Mycroft Core.
#
# Mycroft Core is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mycroft Core is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mycroft Core. If not, see <http://www.gnu.org/licenses/>.
from threading import Thread
from time import sleep
import random
from adapt.intent import IntentBuilder
from mycroft.messagebus.message import Message
from mycroft.skills.LILACS_core.question_parser import LILACSQuestionParser
from mycroft.skills.LILACS_knowledge.knowledgeservice import KnowledgeService
from mycroft.skills.core import MycroftSkill
from mycroft.util.log import getLogger
__author__ = 'jarbas'
logger = getLogger(__name__)
class LILACSChatbotSkill(MycroftSkill):
# https://github.com/ElliotTheRobot/LILACS-mycroft-core/issues/19
def __init__(self):
super(LILACSChatbotSkill, self).__init__(name="ChatbotSkill")
# initialize your variables
self.reload_skill = False
self.active = True
self.parser = None
self.service = None
self.TIMEOUT = 2
def initialize(self):
# register intents
self.parser = LILACSQuestionParser()
self.service = KnowledgeService(self.emitter)
self.build_intents()
# make thread to keep active
self.make_bump_thread()
def ping(self):
while True:
i = 0
if self.active:
self.emitter.emit(Message("recognizer_loop:utterance", {"source": "LILACS_chatbot_skill",
"utterances": [
"bump chat to active skill list"]}))
while i < 60 * self.TIMEOUT:
i += 1
sleep(1)
i = 0
def make_bump_thread(self):
timer_thread = Thread(target=self.ping)
timer_thread.setDaemon(True)
timer_thread.start()
def build_intents(self):
# build intents
deactivate_intent = IntentBuilder("DeactivateChatbotIntent") \
.require("deactivateChatBotKeyword").build()
activate_intent=IntentBuilder("ActivateChatbotIntent") \
.require("activateChatBotKeyword").build()
bump_intent = IntentBuilder("BumpChatBotSkillIntent"). \
require("bumpChatBotKeyword").build()
# register intents
self.register_intent(deactivate_intent, self.handle_deactivate_intent)
self.register_intent(activate_intent, self.handle_activate_intent)
self.register_intent(bump_intent, self.handle_set_on_top_active_list())
def handle_set_on_top_active_list(self):
# dummy intent just to bump curiosity skill to top of active skill list
# called on a timer in order to always use converse method
pass
def handle_deactivate_intent(self, message):
self.active = False
self.speak_dialog("chatbot_off")
def handle_activate_intent(self, message):
self.active = True
self.speak_dialog("chatbot_on")
def stop(self):
self.handle_deactivate_intent("global stop")
def converse(self, transcript, lang="en-us"):
# parse 1st utterance for entitys
if self.active and "bump chat" not in transcript[0] and "bump curiosity" not in transcript[0]:
nodes, parents, synonims = self.parser.tag_from_dbpedia(transcript[0])
self.log.info("nodes: " + str(nodes))
self.log.info("parents: " + str(parents))
self.log.info("synonims: " + str(synonims))
# get concept net , talk
possible_responses = []
for node in nodes:
try:
dict = self.service.adquire(node, "concept net")
usages = dict["concept net"]["surfaceText"]
for usage in usages:
possible_responses.append(usage.replace("[", "").replace("]", ""))
except:
self.log.info("could not get reply for node " + node)
try:
# say something random
reply = random.choice(possible_responses)
self.speak(reply)
return True
except:
self.log.error("Could not get chatbot response for: " + transcript[0])
# dont know what to say
# TODO ask user a question and play du,mb
return False
# tell intent skill you did not handle intent
return False
def create_skill():
<|fim_middle|>
<|fim▁end|> | return LILACSChatbotSkill() |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># Copyright 2016 Mycroft AI, Inc.
#
# This file is part of Mycroft Core.
#
# Mycroft Core is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mycroft Core is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mycroft Core. If not, see <http://www.gnu.org/licenses/>.
from threading import Thread
from time import sleep
import random
from adapt.intent import IntentBuilder
from mycroft.messagebus.message import Message
from mycroft.skills.LILACS_core.question_parser import LILACSQuestionParser
from mycroft.skills.LILACS_knowledge.knowledgeservice import KnowledgeService
from mycroft.skills.core import MycroftSkill
from mycroft.util.log import getLogger
__author__ = 'jarbas'
logger = getLogger(__name__)
class LILACSChatbotSkill(MycroftSkill):
# https://github.com/ElliotTheRobot/LILACS-mycroft-core/issues/19
def __init__(self):
super(LILACSChatbotSkill, self).__init__(name="ChatbotSkill")
# initialize your variables
self.reload_skill = False
self.active = True
self.parser = None
self.service = None
self.TIMEOUT = 2
def initialize(self):
# register intents
self.parser = LILACSQuestionParser()
self.service = KnowledgeService(self.emitter)
self.build_intents()
# make thread to keep active
self.make_bump_thread()
def ping(self):
while True:
i = 0
if self.active:
<|fim_middle|>
while i < 60 * self.TIMEOUT:
i += 1
sleep(1)
i = 0
def make_bump_thread(self):
timer_thread = Thread(target=self.ping)
timer_thread.setDaemon(True)
timer_thread.start()
def build_intents(self):
# build intents
deactivate_intent = IntentBuilder("DeactivateChatbotIntent") \
.require("deactivateChatBotKeyword").build()
activate_intent=IntentBuilder("ActivateChatbotIntent") \
.require("activateChatBotKeyword").build()
bump_intent = IntentBuilder("BumpChatBotSkillIntent"). \
require("bumpChatBotKeyword").build()
# register intents
self.register_intent(deactivate_intent, self.handle_deactivate_intent)
self.register_intent(activate_intent, self.handle_activate_intent)
self.register_intent(bump_intent, self.handle_set_on_top_active_list())
def handle_set_on_top_active_list(self):
# dummy intent just to bump curiosity skill to top of active skill list
# called on a timer in order to always use converse method
pass
def handle_deactivate_intent(self, message):
self.active = False
self.speak_dialog("chatbot_off")
def handle_activate_intent(self, message):
self.active = True
self.speak_dialog("chatbot_on")
def stop(self):
self.handle_deactivate_intent("global stop")
def converse(self, transcript, lang="en-us"):
# parse 1st utterance for entitys
if self.active and "bump chat" not in transcript[0] and "bump curiosity" not in transcript[0]:
nodes, parents, synonims = self.parser.tag_from_dbpedia(transcript[0])
self.log.info("nodes: " + str(nodes))
self.log.info("parents: " + str(parents))
self.log.info("synonims: " + str(synonims))
# get concept net , talk
possible_responses = []
for node in nodes:
try:
dict = self.service.adquire(node, "concept net")
usages = dict["concept net"]["surfaceText"]
for usage in usages:
possible_responses.append(usage.replace("[", "").replace("]", ""))
except:
self.log.info("could not get reply for node " + node)
try:
# say something random
reply = random.choice(possible_responses)
self.speak(reply)
return True
except:
self.log.error("Could not get chatbot response for: " + transcript[0])
# dont know what to say
# TODO ask user a question and play du,mb
return False
# tell intent skill you did not handle intent
return False
def create_skill():
return LILACSChatbotSkill()<|fim▁end|> | self.emitter.emit(Message("recognizer_loop:utterance", {"source": "LILACS_chatbot_skill",
"utterances": [
"bump chat to active skill list"]})) |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># Copyright 2016 Mycroft AI, Inc.
#
# This file is part of Mycroft Core.
#
# Mycroft Core is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mycroft Core is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mycroft Core. If not, see <http://www.gnu.org/licenses/>.
from threading import Thread
from time import sleep
import random
from adapt.intent import IntentBuilder
from mycroft.messagebus.message import Message
from mycroft.skills.LILACS_core.question_parser import LILACSQuestionParser
from mycroft.skills.LILACS_knowledge.knowledgeservice import KnowledgeService
from mycroft.skills.core import MycroftSkill
from mycroft.util.log import getLogger
__author__ = 'jarbas'
logger = getLogger(__name__)
class LILACSChatbotSkill(MycroftSkill):
# https://github.com/ElliotTheRobot/LILACS-mycroft-core/issues/19
def __init__(self):
super(LILACSChatbotSkill, self).__init__(name="ChatbotSkill")
# initialize your variables
self.reload_skill = False
self.active = True
self.parser = None
self.service = None
self.TIMEOUT = 2
def initialize(self):
# register intents
self.parser = LILACSQuestionParser()
self.service = KnowledgeService(self.emitter)
self.build_intents()
# make thread to keep active
self.make_bump_thread()
def ping(self):
while True:
i = 0
if self.active:
self.emitter.emit(Message("recognizer_loop:utterance", {"source": "LILACS_chatbot_skill",
"utterances": [
"bump chat to active skill list"]}))
while i < 60 * self.TIMEOUT:
i += 1
sleep(1)
i = 0
def make_bump_thread(self):
timer_thread = Thread(target=self.ping)
timer_thread.setDaemon(True)
timer_thread.start()
def build_intents(self):
# build intents
deactivate_intent = IntentBuilder("DeactivateChatbotIntent") \
.require("deactivateChatBotKeyword").build()
activate_intent=IntentBuilder("ActivateChatbotIntent") \
.require("activateChatBotKeyword").build()
bump_intent = IntentBuilder("BumpChatBotSkillIntent"). \
require("bumpChatBotKeyword").build()
# register intents
self.register_intent(deactivate_intent, self.handle_deactivate_intent)
self.register_intent(activate_intent, self.handle_activate_intent)
self.register_intent(bump_intent, self.handle_set_on_top_active_list())
def handle_set_on_top_active_list(self):
# dummy intent just to bump curiosity skill to top of active skill list
# called on a timer in order to always use converse method
pass
def handle_deactivate_intent(self, message):
self.active = False
self.speak_dialog("chatbot_off")
def handle_activate_intent(self, message):
self.active = True
self.speak_dialog("chatbot_on")
def stop(self):
self.handle_deactivate_intent("global stop")
def converse(self, transcript, lang="en-us"):
# parse 1st utterance for entitys
if self.active and "bump chat" not in transcript[0] and "bump curiosity" not in transcript[0]:
<|fim_middle|>
# tell intent skill you did not handle intent
return False
def create_skill():
return LILACSChatbotSkill()<|fim▁end|> | nodes, parents, synonims = self.parser.tag_from_dbpedia(transcript[0])
self.log.info("nodes: " + str(nodes))
self.log.info("parents: " + str(parents))
self.log.info("synonims: " + str(synonims))
# get concept net , talk
possible_responses = []
for node in nodes:
try:
dict = self.service.adquire(node, "concept net")
usages = dict["concept net"]["surfaceText"]
for usage in usages:
possible_responses.append(usage.replace("[", "").replace("]", ""))
except:
self.log.info("could not get reply for node " + node)
try:
# say something random
reply = random.choice(possible_responses)
self.speak(reply)
return True
except:
self.log.error("Could not get chatbot response for: " + transcript[0])
# dont know what to say
# TODO ask user a question and play du,mb
return False |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># Copyright 2016 Mycroft AI, Inc.
#
# This file is part of Mycroft Core.
#
# Mycroft Core is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mycroft Core is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mycroft Core. If not, see <http://www.gnu.org/licenses/>.
from threading import Thread
from time import sleep
import random
from adapt.intent import IntentBuilder
from mycroft.messagebus.message import Message
from mycroft.skills.LILACS_core.question_parser import LILACSQuestionParser
from mycroft.skills.LILACS_knowledge.knowledgeservice import KnowledgeService
from mycroft.skills.core import MycroftSkill
from mycroft.util.log import getLogger
__author__ = 'jarbas'
logger = getLogger(__name__)
class LILACSChatbotSkill(MycroftSkill):
# https://github.com/ElliotTheRobot/LILACS-mycroft-core/issues/19
def <|fim_middle|>(self):
super(LILACSChatbotSkill, self).__init__(name="ChatbotSkill")
# initialize your variables
self.reload_skill = False
self.active = True
self.parser = None
self.service = None
self.TIMEOUT = 2
def initialize(self):
# register intents
self.parser = LILACSQuestionParser()
self.service = KnowledgeService(self.emitter)
self.build_intents()
# make thread to keep active
self.make_bump_thread()
def ping(self):
while True:
i = 0
if self.active:
self.emitter.emit(Message("recognizer_loop:utterance", {"source": "LILACS_chatbot_skill",
"utterances": [
"bump chat to active skill list"]}))
while i < 60 * self.TIMEOUT:
i += 1
sleep(1)
i = 0
def make_bump_thread(self):
timer_thread = Thread(target=self.ping)
timer_thread.setDaemon(True)
timer_thread.start()
def build_intents(self):
# build intents
deactivate_intent = IntentBuilder("DeactivateChatbotIntent") \
.require("deactivateChatBotKeyword").build()
activate_intent=IntentBuilder("ActivateChatbotIntent") \
.require("activateChatBotKeyword").build()
bump_intent = IntentBuilder("BumpChatBotSkillIntent"). \
require("bumpChatBotKeyword").build()
# register intents
self.register_intent(deactivate_intent, self.handle_deactivate_intent)
self.register_intent(activate_intent, self.handle_activate_intent)
self.register_intent(bump_intent, self.handle_set_on_top_active_list())
def handle_set_on_top_active_list(self):
# dummy intent just to bump curiosity skill to top of active skill list
# called on a timer in order to always use converse method
pass
def handle_deactivate_intent(self, message):
self.active = False
self.speak_dialog("chatbot_off")
def handle_activate_intent(self, message):
self.active = True
self.speak_dialog("chatbot_on")
def stop(self):
self.handle_deactivate_intent("global stop")
def converse(self, transcript, lang="en-us"):
# parse 1st utterance for entitys
if self.active and "bump chat" not in transcript[0] and "bump curiosity" not in transcript[0]:
nodes, parents, synonims = self.parser.tag_from_dbpedia(transcript[0])
self.log.info("nodes: " + str(nodes))
self.log.info("parents: " + str(parents))
self.log.info("synonims: " + str(synonims))
# get concept net , talk
possible_responses = []
for node in nodes:
try:
dict = self.service.adquire(node, "concept net")
usages = dict["concept net"]["surfaceText"]
for usage in usages:
possible_responses.append(usage.replace("[", "").replace("]", ""))
except:
self.log.info("could not get reply for node " + node)
try:
# say something random
reply = random.choice(possible_responses)
self.speak(reply)
return True
except:
self.log.error("Could not get chatbot response for: " + transcript[0])
# dont know what to say
# TODO ask user a question and play du,mb
return False
# tell intent skill you did not handle intent
return False
def create_skill():
return LILACSChatbotSkill()<|fim▁end|> | __init__ |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># Copyright 2016 Mycroft AI, Inc.
#
# This file is part of Mycroft Core.
#
# Mycroft Core is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mycroft Core is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mycroft Core. If not, see <http://www.gnu.org/licenses/>.
from threading import Thread
from time import sleep
import random
from adapt.intent import IntentBuilder
from mycroft.messagebus.message import Message
from mycroft.skills.LILACS_core.question_parser import LILACSQuestionParser
from mycroft.skills.LILACS_knowledge.knowledgeservice import KnowledgeService
from mycroft.skills.core import MycroftSkill
from mycroft.util.log import getLogger
__author__ = 'jarbas'
logger = getLogger(__name__)
class LILACSChatbotSkill(MycroftSkill):
# https://github.com/ElliotTheRobot/LILACS-mycroft-core/issues/19
def __init__(self):
super(LILACSChatbotSkill, self).__init__(name="ChatbotSkill")
# initialize your variables
self.reload_skill = False
self.active = True
self.parser = None
self.service = None
self.TIMEOUT = 2
def <|fim_middle|>(self):
# register intents
self.parser = LILACSQuestionParser()
self.service = KnowledgeService(self.emitter)
self.build_intents()
# make thread to keep active
self.make_bump_thread()
def ping(self):
while True:
i = 0
if self.active:
self.emitter.emit(Message("recognizer_loop:utterance", {"source": "LILACS_chatbot_skill",
"utterances": [
"bump chat to active skill list"]}))
while i < 60 * self.TIMEOUT:
i += 1
sleep(1)
i = 0
def make_bump_thread(self):
timer_thread = Thread(target=self.ping)
timer_thread.setDaemon(True)
timer_thread.start()
def build_intents(self):
# build intents
deactivate_intent = IntentBuilder("DeactivateChatbotIntent") \
.require("deactivateChatBotKeyword").build()
activate_intent=IntentBuilder("ActivateChatbotIntent") \
.require("activateChatBotKeyword").build()
bump_intent = IntentBuilder("BumpChatBotSkillIntent"). \
require("bumpChatBotKeyword").build()
# register intents
self.register_intent(deactivate_intent, self.handle_deactivate_intent)
self.register_intent(activate_intent, self.handle_activate_intent)
self.register_intent(bump_intent, self.handle_set_on_top_active_list())
def handle_set_on_top_active_list(self):
# dummy intent just to bump curiosity skill to top of active skill list
# called on a timer in order to always use converse method
pass
def handle_deactivate_intent(self, message):
self.active = False
self.speak_dialog("chatbot_off")
def handle_activate_intent(self, message):
self.active = True
self.speak_dialog("chatbot_on")
def stop(self):
self.handle_deactivate_intent("global stop")
def converse(self, transcript, lang="en-us"):
# parse 1st utterance for entitys
if self.active and "bump chat" not in transcript[0] and "bump curiosity" not in transcript[0]:
nodes, parents, synonims = self.parser.tag_from_dbpedia(transcript[0])
self.log.info("nodes: " + str(nodes))
self.log.info("parents: " + str(parents))
self.log.info("synonims: " + str(synonims))
# get concept net , talk
possible_responses = []
for node in nodes:
try:
dict = self.service.adquire(node, "concept net")
usages = dict["concept net"]["surfaceText"]
for usage in usages:
possible_responses.append(usage.replace("[", "").replace("]", ""))
except:
self.log.info("could not get reply for node " + node)
try:
# say something random
reply = random.choice(possible_responses)
self.speak(reply)
return True
except:
self.log.error("Could not get chatbot response for: " + transcript[0])
# dont know what to say
# TODO ask user a question and play du,mb
return False
# tell intent skill you did not handle intent
return False
def create_skill():
return LILACSChatbotSkill()<|fim▁end|> | initialize |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># Copyright 2016 Mycroft AI, Inc.
#
# This file is part of Mycroft Core.
#
# Mycroft Core is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mycroft Core is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mycroft Core. If not, see <http://www.gnu.org/licenses/>.
from threading import Thread
from time import sleep
import random
from adapt.intent import IntentBuilder
from mycroft.messagebus.message import Message
from mycroft.skills.LILACS_core.question_parser import LILACSQuestionParser
from mycroft.skills.LILACS_knowledge.knowledgeservice import KnowledgeService
from mycroft.skills.core import MycroftSkill
from mycroft.util.log import getLogger
__author__ = 'jarbas'
logger = getLogger(__name__)
class LILACSChatbotSkill(MycroftSkill):
# https://github.com/ElliotTheRobot/LILACS-mycroft-core/issues/19
def __init__(self):
super(LILACSChatbotSkill, self).__init__(name="ChatbotSkill")
# initialize your variables
self.reload_skill = False
self.active = True
self.parser = None
self.service = None
self.TIMEOUT = 2
def initialize(self):
# register intents
self.parser = LILACSQuestionParser()
self.service = KnowledgeService(self.emitter)
self.build_intents()
# make thread to keep active
self.make_bump_thread()
def <|fim_middle|>(self):
while True:
i = 0
if self.active:
self.emitter.emit(Message("recognizer_loop:utterance", {"source": "LILACS_chatbot_skill",
"utterances": [
"bump chat to active skill list"]}))
while i < 60 * self.TIMEOUT:
i += 1
sleep(1)
i = 0
def make_bump_thread(self):
timer_thread = Thread(target=self.ping)
timer_thread.setDaemon(True)
timer_thread.start()
def build_intents(self):
# build intents
deactivate_intent = IntentBuilder("DeactivateChatbotIntent") \
.require("deactivateChatBotKeyword").build()
activate_intent=IntentBuilder("ActivateChatbotIntent") \
.require("activateChatBotKeyword").build()
bump_intent = IntentBuilder("BumpChatBotSkillIntent"). \
require("bumpChatBotKeyword").build()
# register intents
self.register_intent(deactivate_intent, self.handle_deactivate_intent)
self.register_intent(activate_intent, self.handle_activate_intent)
self.register_intent(bump_intent, self.handle_set_on_top_active_list())
def handle_set_on_top_active_list(self):
# dummy intent just to bump curiosity skill to top of active skill list
# called on a timer in order to always use converse method
pass
def handle_deactivate_intent(self, message):
self.active = False
self.speak_dialog("chatbot_off")
def handle_activate_intent(self, message):
self.active = True
self.speak_dialog("chatbot_on")
def stop(self):
self.handle_deactivate_intent("global stop")
def converse(self, transcript, lang="en-us"):
# parse 1st utterance for entitys
if self.active and "bump chat" not in transcript[0] and "bump curiosity" not in transcript[0]:
nodes, parents, synonims = self.parser.tag_from_dbpedia(transcript[0])
self.log.info("nodes: " + str(nodes))
self.log.info("parents: " + str(parents))
self.log.info("synonims: " + str(synonims))
# get concept net , talk
possible_responses = []
for node in nodes:
try:
dict = self.service.adquire(node, "concept net")
usages = dict["concept net"]["surfaceText"]
for usage in usages:
possible_responses.append(usage.replace("[", "").replace("]", ""))
except:
self.log.info("could not get reply for node " + node)
try:
# say something random
reply = random.choice(possible_responses)
self.speak(reply)
return True
except:
self.log.error("Could not get chatbot response for: " + transcript[0])
# dont know what to say
# TODO ask user a question and play du,mb
return False
# tell intent skill you did not handle intent
return False
def create_skill():
return LILACSChatbotSkill()<|fim▁end|> | ping |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># Copyright 2016 Mycroft AI, Inc.
#
# This file is part of Mycroft Core.
#
# Mycroft Core is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mycroft Core is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mycroft Core. If not, see <http://www.gnu.org/licenses/>.
from threading import Thread
from time import sleep
import random
from adapt.intent import IntentBuilder
from mycroft.messagebus.message import Message
from mycroft.skills.LILACS_core.question_parser import LILACSQuestionParser
from mycroft.skills.LILACS_knowledge.knowledgeservice import KnowledgeService
from mycroft.skills.core import MycroftSkill
from mycroft.util.log import getLogger
__author__ = 'jarbas'
logger = getLogger(__name__)
class LILACSChatbotSkill(MycroftSkill):
# https://github.com/ElliotTheRobot/LILACS-mycroft-core/issues/19
def __init__(self):
super(LILACSChatbotSkill, self).__init__(name="ChatbotSkill")
# initialize your variables
self.reload_skill = False
self.active = True
self.parser = None
self.service = None
self.TIMEOUT = 2
def initialize(self):
# register intents
self.parser = LILACSQuestionParser()
self.service = KnowledgeService(self.emitter)
self.build_intents()
# make thread to keep active
self.make_bump_thread()
def ping(self):
while True:
i = 0
if self.active:
self.emitter.emit(Message("recognizer_loop:utterance", {"source": "LILACS_chatbot_skill",
"utterances": [
"bump chat to active skill list"]}))
while i < 60 * self.TIMEOUT:
i += 1
sleep(1)
i = 0
def <|fim_middle|>(self):
timer_thread = Thread(target=self.ping)
timer_thread.setDaemon(True)
timer_thread.start()
def build_intents(self):
# build intents
deactivate_intent = IntentBuilder("DeactivateChatbotIntent") \
.require("deactivateChatBotKeyword").build()
activate_intent=IntentBuilder("ActivateChatbotIntent") \
.require("activateChatBotKeyword").build()
bump_intent = IntentBuilder("BumpChatBotSkillIntent"). \
require("bumpChatBotKeyword").build()
# register intents
self.register_intent(deactivate_intent, self.handle_deactivate_intent)
self.register_intent(activate_intent, self.handle_activate_intent)
self.register_intent(bump_intent, self.handle_set_on_top_active_list())
def handle_set_on_top_active_list(self):
# dummy intent just to bump curiosity skill to top of active skill list
# called on a timer in order to always use converse method
pass
def handle_deactivate_intent(self, message):
self.active = False
self.speak_dialog("chatbot_off")
def handle_activate_intent(self, message):
self.active = True
self.speak_dialog("chatbot_on")
def stop(self):
self.handle_deactivate_intent("global stop")
def converse(self, transcript, lang="en-us"):
# parse 1st utterance for entitys
if self.active and "bump chat" not in transcript[0] and "bump curiosity" not in transcript[0]:
nodes, parents, synonims = self.parser.tag_from_dbpedia(transcript[0])
self.log.info("nodes: " + str(nodes))
self.log.info("parents: " + str(parents))
self.log.info("synonims: " + str(synonims))
# get concept net , talk
possible_responses = []
for node in nodes:
try:
dict = self.service.adquire(node, "concept net")
usages = dict["concept net"]["surfaceText"]
for usage in usages:
possible_responses.append(usage.replace("[", "").replace("]", ""))
except:
self.log.info("could not get reply for node " + node)
try:
# say something random
reply = random.choice(possible_responses)
self.speak(reply)
return True
except:
self.log.error("Could not get chatbot response for: " + transcript[0])
# dont know what to say
# TODO ask user a question and play du,mb
return False
# tell intent skill you did not handle intent
return False
def create_skill():
return LILACSChatbotSkill()<|fim▁end|> | make_bump_thread |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># Copyright 2016 Mycroft AI, Inc.
#
# This file is part of Mycroft Core.
#
# Mycroft Core is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mycroft Core is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mycroft Core. If not, see <http://www.gnu.org/licenses/>.
from threading import Thread
from time import sleep
import random
from adapt.intent import IntentBuilder
from mycroft.messagebus.message import Message
from mycroft.skills.LILACS_core.question_parser import LILACSQuestionParser
from mycroft.skills.LILACS_knowledge.knowledgeservice import KnowledgeService
from mycroft.skills.core import MycroftSkill
from mycroft.util.log import getLogger
__author__ = 'jarbas'
logger = getLogger(__name__)
class LILACSChatbotSkill(MycroftSkill):
# https://github.com/ElliotTheRobot/LILACS-mycroft-core/issues/19
def __init__(self):
super(LILACSChatbotSkill, self).__init__(name="ChatbotSkill")
# initialize your variables
self.reload_skill = False
self.active = True
self.parser = None
self.service = None
self.TIMEOUT = 2
def initialize(self):
# register intents
self.parser = LILACSQuestionParser()
self.service = KnowledgeService(self.emitter)
self.build_intents()
# make thread to keep active
self.make_bump_thread()
def ping(self):
while True:
i = 0
if self.active:
self.emitter.emit(Message("recognizer_loop:utterance", {"source": "LILACS_chatbot_skill",
"utterances": [
"bump chat to active skill list"]}))
while i < 60 * self.TIMEOUT:
i += 1
sleep(1)
i = 0
def make_bump_thread(self):
timer_thread = Thread(target=self.ping)
timer_thread.setDaemon(True)
timer_thread.start()
def <|fim_middle|>(self):
# build intents
deactivate_intent = IntentBuilder("DeactivateChatbotIntent") \
.require("deactivateChatBotKeyword").build()
activate_intent=IntentBuilder("ActivateChatbotIntent") \
.require("activateChatBotKeyword").build()
bump_intent = IntentBuilder("BumpChatBotSkillIntent"). \
require("bumpChatBotKeyword").build()
# register intents
self.register_intent(deactivate_intent, self.handle_deactivate_intent)
self.register_intent(activate_intent, self.handle_activate_intent)
self.register_intent(bump_intent, self.handle_set_on_top_active_list())
def handle_set_on_top_active_list(self):
# dummy intent just to bump curiosity skill to top of active skill list
# called on a timer in order to always use converse method
pass
def handle_deactivate_intent(self, message):
self.active = False
self.speak_dialog("chatbot_off")
def handle_activate_intent(self, message):
self.active = True
self.speak_dialog("chatbot_on")
def stop(self):
self.handle_deactivate_intent("global stop")
def converse(self, transcript, lang="en-us"):
# parse 1st utterance for entitys
if self.active and "bump chat" not in transcript[0] and "bump curiosity" not in transcript[0]:
nodes, parents, synonims = self.parser.tag_from_dbpedia(transcript[0])
self.log.info("nodes: " + str(nodes))
self.log.info("parents: " + str(parents))
self.log.info("synonims: " + str(synonims))
# get concept net , talk
possible_responses = []
for node in nodes:
try:
dict = self.service.adquire(node, "concept net")
usages = dict["concept net"]["surfaceText"]
for usage in usages:
possible_responses.append(usage.replace("[", "").replace("]", ""))
except:
self.log.info("could not get reply for node " + node)
try:
# say something random
reply = random.choice(possible_responses)
self.speak(reply)
return True
except:
self.log.error("Could not get chatbot response for: " + transcript[0])
# dont know what to say
# TODO ask user a question and play du,mb
return False
# tell intent skill you did not handle intent
return False
def create_skill():
return LILACSChatbotSkill()<|fim▁end|> | build_intents |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># Copyright 2016 Mycroft AI, Inc.
#
# This file is part of Mycroft Core.
#
# Mycroft Core is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mycroft Core is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mycroft Core. If not, see <http://www.gnu.org/licenses/>.
from threading import Thread
from time import sleep
import random
from adapt.intent import IntentBuilder
from mycroft.messagebus.message import Message
from mycroft.skills.LILACS_core.question_parser import LILACSQuestionParser
from mycroft.skills.LILACS_knowledge.knowledgeservice import KnowledgeService
from mycroft.skills.core import MycroftSkill
from mycroft.util.log import getLogger
__author__ = 'jarbas'
logger = getLogger(__name__)
class LILACSChatbotSkill(MycroftSkill):
# https://github.com/ElliotTheRobot/LILACS-mycroft-core/issues/19
def __init__(self):
super(LILACSChatbotSkill, self).__init__(name="ChatbotSkill")
# initialize your variables
self.reload_skill = False
self.active = True
self.parser = None
self.service = None
self.TIMEOUT = 2
def initialize(self):
# register intents
self.parser = LILACSQuestionParser()
self.service = KnowledgeService(self.emitter)
self.build_intents()
# make thread to keep active
self.make_bump_thread()
def ping(self):
while True:
i = 0
if self.active:
self.emitter.emit(Message("recognizer_loop:utterance", {"source": "LILACS_chatbot_skill",
"utterances": [
"bump chat to active skill list"]}))
while i < 60 * self.TIMEOUT:
i += 1
sleep(1)
i = 0
def make_bump_thread(self):
timer_thread = Thread(target=self.ping)
timer_thread.setDaemon(True)
timer_thread.start()
def build_intents(self):
# build intents
deactivate_intent = IntentBuilder("DeactivateChatbotIntent") \
.require("deactivateChatBotKeyword").build()
activate_intent=IntentBuilder("ActivateChatbotIntent") \
.require("activateChatBotKeyword").build()
bump_intent = IntentBuilder("BumpChatBotSkillIntent"). \
require("bumpChatBotKeyword").build()
# register intents
self.register_intent(deactivate_intent, self.handle_deactivate_intent)
self.register_intent(activate_intent, self.handle_activate_intent)
self.register_intent(bump_intent, self.handle_set_on_top_active_list())
def <|fim_middle|>(self):
# dummy intent just to bump curiosity skill to top of active skill list
# called on a timer in order to always use converse method
pass
def handle_deactivate_intent(self, message):
self.active = False
self.speak_dialog("chatbot_off")
def handle_activate_intent(self, message):
self.active = True
self.speak_dialog("chatbot_on")
def stop(self):
self.handle_deactivate_intent("global stop")
def converse(self, transcript, lang="en-us"):
# parse 1st utterance for entitys
if self.active and "bump chat" not in transcript[0] and "bump curiosity" not in transcript[0]:
nodes, parents, synonims = self.parser.tag_from_dbpedia(transcript[0])
self.log.info("nodes: " + str(nodes))
self.log.info("parents: " + str(parents))
self.log.info("synonims: " + str(synonims))
# get concept net , talk
possible_responses = []
for node in nodes:
try:
dict = self.service.adquire(node, "concept net")
usages = dict["concept net"]["surfaceText"]
for usage in usages:
possible_responses.append(usage.replace("[", "").replace("]", ""))
except:
self.log.info("could not get reply for node " + node)
try:
# say something random
reply = random.choice(possible_responses)
self.speak(reply)
return True
except:
self.log.error("Could not get chatbot response for: " + transcript[0])
# dont know what to say
# TODO ask user a question and play du,mb
return False
# tell intent skill you did not handle intent
return False
def create_skill():
return LILACSChatbotSkill()<|fim▁end|> | handle_set_on_top_active_list |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># Copyright 2016 Mycroft AI, Inc.
#
# This file is part of Mycroft Core.
#
# Mycroft Core is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mycroft Core is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mycroft Core. If not, see <http://www.gnu.org/licenses/>.
from threading import Thread
from time import sleep
import random
from adapt.intent import IntentBuilder
from mycroft.messagebus.message import Message
from mycroft.skills.LILACS_core.question_parser import LILACSQuestionParser
from mycroft.skills.LILACS_knowledge.knowledgeservice import KnowledgeService
from mycroft.skills.core import MycroftSkill
from mycroft.util.log import getLogger
__author__ = 'jarbas'
logger = getLogger(__name__)
class LILACSChatbotSkill(MycroftSkill):
# https://github.com/ElliotTheRobot/LILACS-mycroft-core/issues/19
def __init__(self):
super(LILACSChatbotSkill, self).__init__(name="ChatbotSkill")
# initialize your variables
self.reload_skill = False
self.active = True
self.parser = None
self.service = None
self.TIMEOUT = 2
def initialize(self):
# register intents
self.parser = LILACSQuestionParser()
self.service = KnowledgeService(self.emitter)
self.build_intents()
# make thread to keep active
self.make_bump_thread()
def ping(self):
while True:
i = 0
if self.active:
self.emitter.emit(Message("recognizer_loop:utterance", {"source": "LILACS_chatbot_skill",
"utterances": [
"bump chat to active skill list"]}))
while i < 60 * self.TIMEOUT:
i += 1
sleep(1)
i = 0
def make_bump_thread(self):
timer_thread = Thread(target=self.ping)
timer_thread.setDaemon(True)
timer_thread.start()
def build_intents(self):
# build intents
deactivate_intent = IntentBuilder("DeactivateChatbotIntent") \
.require("deactivateChatBotKeyword").build()
activate_intent=IntentBuilder("ActivateChatbotIntent") \
.require("activateChatBotKeyword").build()
bump_intent = IntentBuilder("BumpChatBotSkillIntent"). \
require("bumpChatBotKeyword").build()
# register intents
self.register_intent(deactivate_intent, self.handle_deactivate_intent)
self.register_intent(activate_intent, self.handle_activate_intent)
self.register_intent(bump_intent, self.handle_set_on_top_active_list())
def handle_set_on_top_active_list(self):
# dummy intent just to bump curiosity skill to top of active skill list
# called on a timer in order to always use converse method
pass
def <|fim_middle|>(self, message):
self.active = False
self.speak_dialog("chatbot_off")
def handle_activate_intent(self, message):
self.active = True
self.speak_dialog("chatbot_on")
def stop(self):
self.handle_deactivate_intent("global stop")
def converse(self, transcript, lang="en-us"):
# parse 1st utterance for entitys
if self.active and "bump chat" not in transcript[0] and "bump curiosity" not in transcript[0]:
nodes, parents, synonims = self.parser.tag_from_dbpedia(transcript[0])
self.log.info("nodes: " + str(nodes))
self.log.info("parents: " + str(parents))
self.log.info("synonims: " + str(synonims))
# get concept net , talk
possible_responses = []
for node in nodes:
try:
dict = self.service.adquire(node, "concept net")
usages = dict["concept net"]["surfaceText"]
for usage in usages:
possible_responses.append(usage.replace("[", "").replace("]", ""))
except:
self.log.info("could not get reply for node " + node)
try:
# say something random
reply = random.choice(possible_responses)
self.speak(reply)
return True
except:
self.log.error("Could not get chatbot response for: " + transcript[0])
# dont know what to say
# TODO ask user a question and play du,mb
return False
# tell intent skill you did not handle intent
return False
def create_skill():
return LILACSChatbotSkill()<|fim▁end|> | handle_deactivate_intent |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># Copyright 2016 Mycroft AI, Inc.
#
# This file is part of Mycroft Core.
#
# Mycroft Core is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mycroft Core is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mycroft Core. If not, see <http://www.gnu.org/licenses/>.
from threading import Thread
from time import sleep
import random
from adapt.intent import IntentBuilder
from mycroft.messagebus.message import Message
from mycroft.skills.LILACS_core.question_parser import LILACSQuestionParser
from mycroft.skills.LILACS_knowledge.knowledgeservice import KnowledgeService
from mycroft.skills.core import MycroftSkill
from mycroft.util.log import getLogger
__author__ = 'jarbas'
logger = getLogger(__name__)
class LILACSChatbotSkill(MycroftSkill):
# https://github.com/ElliotTheRobot/LILACS-mycroft-core/issues/19
def __init__(self):
super(LILACSChatbotSkill, self).__init__(name="ChatbotSkill")
# initialize your variables
self.reload_skill = False
self.active = True
self.parser = None
self.service = None
self.TIMEOUT = 2
def initialize(self):
# register intents
self.parser = LILACSQuestionParser()
self.service = KnowledgeService(self.emitter)
self.build_intents()
# make thread to keep active
self.make_bump_thread()
def ping(self):
while True:
i = 0
if self.active:
self.emitter.emit(Message("recognizer_loop:utterance", {"source": "LILACS_chatbot_skill",
"utterances": [
"bump chat to active skill list"]}))
while i < 60 * self.TIMEOUT:
i += 1
sleep(1)
i = 0
def make_bump_thread(self):
timer_thread = Thread(target=self.ping)
timer_thread.setDaemon(True)
timer_thread.start()
def build_intents(self):
# build intents
deactivate_intent = IntentBuilder("DeactivateChatbotIntent") \
.require("deactivateChatBotKeyword").build()
activate_intent=IntentBuilder("ActivateChatbotIntent") \
.require("activateChatBotKeyword").build()
bump_intent = IntentBuilder("BumpChatBotSkillIntent"). \
require("bumpChatBotKeyword").build()
# register intents
self.register_intent(deactivate_intent, self.handle_deactivate_intent)
self.register_intent(activate_intent, self.handle_activate_intent)
self.register_intent(bump_intent, self.handle_set_on_top_active_list())
def handle_set_on_top_active_list(self):
# dummy intent just to bump curiosity skill to top of active skill list
# called on a timer in order to always use converse method
pass
def handle_deactivate_intent(self, message):
self.active = False
self.speak_dialog("chatbot_off")
def <|fim_middle|>(self, message):
self.active = True
self.speak_dialog("chatbot_on")
def stop(self):
self.handle_deactivate_intent("global stop")
def converse(self, transcript, lang="en-us"):
# parse 1st utterance for entitys
if self.active and "bump chat" not in transcript[0] and "bump curiosity" not in transcript[0]:
nodes, parents, synonims = self.parser.tag_from_dbpedia(transcript[0])
self.log.info("nodes: " + str(nodes))
self.log.info("parents: " + str(parents))
self.log.info("synonims: " + str(synonims))
# get concept net , talk
possible_responses = []
for node in nodes:
try:
dict = self.service.adquire(node, "concept net")
usages = dict["concept net"]["surfaceText"]
for usage in usages:
possible_responses.append(usage.replace("[", "").replace("]", ""))
except:
self.log.info("could not get reply for node " + node)
try:
# say something random
reply = random.choice(possible_responses)
self.speak(reply)
return True
except:
self.log.error("Could not get chatbot response for: " + transcript[0])
# dont know what to say
# TODO ask user a question and play du,mb
return False
# tell intent skill you did not handle intent
return False
def create_skill():
return LILACSChatbotSkill()<|fim▁end|> | handle_activate_intent |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># Copyright 2016 Mycroft AI, Inc.
#
# This file is part of Mycroft Core.
#
# Mycroft Core is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mycroft Core is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mycroft Core. If not, see <http://www.gnu.org/licenses/>.
from threading import Thread
from time import sleep
import random
from adapt.intent import IntentBuilder
from mycroft.messagebus.message import Message
from mycroft.skills.LILACS_core.question_parser import LILACSQuestionParser
from mycroft.skills.LILACS_knowledge.knowledgeservice import KnowledgeService
from mycroft.skills.core import MycroftSkill
from mycroft.util.log import getLogger
__author__ = 'jarbas'
logger = getLogger(__name__)
class LILACSChatbotSkill(MycroftSkill):
# https://github.com/ElliotTheRobot/LILACS-mycroft-core/issues/19
def __init__(self):
super(LILACSChatbotSkill, self).__init__(name="ChatbotSkill")
# initialize your variables
self.reload_skill = False
self.active = True
self.parser = None
self.service = None
self.TIMEOUT = 2
def initialize(self):
# register intents
self.parser = LILACSQuestionParser()
self.service = KnowledgeService(self.emitter)
self.build_intents()
# make thread to keep active
self.make_bump_thread()
def ping(self):
while True:
i = 0
if self.active:
self.emitter.emit(Message("recognizer_loop:utterance", {"source": "LILACS_chatbot_skill",
"utterances": [
"bump chat to active skill list"]}))
while i < 60 * self.TIMEOUT:
i += 1
sleep(1)
i = 0
def make_bump_thread(self):
timer_thread = Thread(target=self.ping)
timer_thread.setDaemon(True)
timer_thread.start()
def build_intents(self):
# build intents
deactivate_intent = IntentBuilder("DeactivateChatbotIntent") \
.require("deactivateChatBotKeyword").build()
activate_intent=IntentBuilder("ActivateChatbotIntent") \
.require("activateChatBotKeyword").build()
bump_intent = IntentBuilder("BumpChatBotSkillIntent"). \
require("bumpChatBotKeyword").build()
# register intents
self.register_intent(deactivate_intent, self.handle_deactivate_intent)
self.register_intent(activate_intent, self.handle_activate_intent)
self.register_intent(bump_intent, self.handle_set_on_top_active_list())
def handle_set_on_top_active_list(self):
# dummy intent just to bump curiosity skill to top of active skill list
# called on a timer in order to always use converse method
pass
def handle_deactivate_intent(self, message):
self.active = False
self.speak_dialog("chatbot_off")
def handle_activate_intent(self, message):
self.active = True
self.speak_dialog("chatbot_on")
def <|fim_middle|>(self):
self.handle_deactivate_intent("global stop")
def converse(self, transcript, lang="en-us"):
# parse 1st utterance for entitys
if self.active and "bump chat" not in transcript[0] and "bump curiosity" not in transcript[0]:
nodes, parents, synonims = self.parser.tag_from_dbpedia(transcript[0])
self.log.info("nodes: " + str(nodes))
self.log.info("parents: " + str(parents))
self.log.info("synonims: " + str(synonims))
# get concept net , talk
possible_responses = []
for node in nodes:
try:
dict = self.service.adquire(node, "concept net")
usages = dict["concept net"]["surfaceText"]
for usage in usages:
possible_responses.append(usage.replace("[", "").replace("]", ""))
except:
self.log.info("could not get reply for node " + node)
try:
# say something random
reply = random.choice(possible_responses)
self.speak(reply)
return True
except:
self.log.error("Could not get chatbot response for: " + transcript[0])
# dont know what to say
# TODO ask user a question and play du,mb
return False
# tell intent skill you did not handle intent
return False
def create_skill():
return LILACSChatbotSkill()<|fim▁end|> | stop |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># Copyright 2016 Mycroft AI, Inc.
#
# This file is part of Mycroft Core.
#
# Mycroft Core is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mycroft Core is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mycroft Core. If not, see <http://www.gnu.org/licenses/>.
from threading import Thread
from time import sleep
import random
from adapt.intent import IntentBuilder
from mycroft.messagebus.message import Message
from mycroft.skills.LILACS_core.question_parser import LILACSQuestionParser
from mycroft.skills.LILACS_knowledge.knowledgeservice import KnowledgeService
from mycroft.skills.core import MycroftSkill
from mycroft.util.log import getLogger
__author__ = 'jarbas'
logger = getLogger(__name__)
class LILACSChatbotSkill(MycroftSkill):
# https://github.com/ElliotTheRobot/LILACS-mycroft-core/issues/19
def __init__(self):
super(LILACSChatbotSkill, self).__init__(name="ChatbotSkill")
# initialize your variables
self.reload_skill = False
self.active = True
self.parser = None
self.service = None
self.TIMEOUT = 2
def initialize(self):
# register intents
self.parser = LILACSQuestionParser()
self.service = KnowledgeService(self.emitter)
self.build_intents()
# make thread to keep active
self.make_bump_thread()
def ping(self):
while True:
i = 0
if self.active:
self.emitter.emit(Message("recognizer_loop:utterance", {"source": "LILACS_chatbot_skill",
"utterances": [
"bump chat to active skill list"]}))
while i < 60 * self.TIMEOUT:
i += 1
sleep(1)
i = 0
def make_bump_thread(self):
timer_thread = Thread(target=self.ping)
timer_thread.setDaemon(True)
timer_thread.start()
def build_intents(self):
# build intents
deactivate_intent = IntentBuilder("DeactivateChatbotIntent") \
.require("deactivateChatBotKeyword").build()
activate_intent=IntentBuilder("ActivateChatbotIntent") \
.require("activateChatBotKeyword").build()
bump_intent = IntentBuilder("BumpChatBotSkillIntent"). \
require("bumpChatBotKeyword").build()
# register intents
self.register_intent(deactivate_intent, self.handle_deactivate_intent)
self.register_intent(activate_intent, self.handle_activate_intent)
self.register_intent(bump_intent, self.handle_set_on_top_active_list())
def handle_set_on_top_active_list(self):
# dummy intent just to bump curiosity skill to top of active skill list
# called on a timer in order to always use converse method
pass
def handle_deactivate_intent(self, message):
self.active = False
self.speak_dialog("chatbot_off")
def handle_activate_intent(self, message):
self.active = True
self.speak_dialog("chatbot_on")
def stop(self):
self.handle_deactivate_intent("global stop")
def <|fim_middle|>(self, transcript, lang="en-us"):
# parse 1st utterance for entitys
if self.active and "bump chat" not in transcript[0] and "bump curiosity" not in transcript[0]:
nodes, parents, synonims = self.parser.tag_from_dbpedia(transcript[0])
self.log.info("nodes: " + str(nodes))
self.log.info("parents: " + str(parents))
self.log.info("synonims: " + str(synonims))
# get concept net , talk
possible_responses = []
for node in nodes:
try:
dict = self.service.adquire(node, "concept net")
usages = dict["concept net"]["surfaceText"]
for usage in usages:
possible_responses.append(usage.replace("[", "").replace("]", ""))
except:
self.log.info("could not get reply for node " + node)
try:
# say something random
reply = random.choice(possible_responses)
self.speak(reply)
return True
except:
self.log.error("Could not get chatbot response for: " + transcript[0])
# dont know what to say
# TODO ask user a question and play du,mb
return False
# tell intent skill you did not handle intent
return False
def create_skill():
return LILACSChatbotSkill()<|fim▁end|> | converse |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># Copyright 2016 Mycroft AI, Inc.
#
# This file is part of Mycroft Core.
#
# Mycroft Core is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mycroft Core is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mycroft Core. If not, see <http://www.gnu.org/licenses/>.
from threading import Thread
from time import sleep
import random
from adapt.intent import IntentBuilder
from mycroft.messagebus.message import Message
from mycroft.skills.LILACS_core.question_parser import LILACSQuestionParser
from mycroft.skills.LILACS_knowledge.knowledgeservice import KnowledgeService
from mycroft.skills.core import MycroftSkill
from mycroft.util.log import getLogger
__author__ = 'jarbas'
logger = getLogger(__name__)
class LILACSChatbotSkill(MycroftSkill):
# https://github.com/ElliotTheRobot/LILACS-mycroft-core/issues/19
def __init__(self):
super(LILACSChatbotSkill, self).__init__(name="ChatbotSkill")
# initialize your variables
self.reload_skill = False
self.active = True
self.parser = None
self.service = None
self.TIMEOUT = 2
def initialize(self):
# register intents
self.parser = LILACSQuestionParser()
self.service = KnowledgeService(self.emitter)
self.build_intents()
# make thread to keep active
self.make_bump_thread()
def ping(self):
while True:
i = 0
if self.active:
self.emitter.emit(Message("recognizer_loop:utterance", {"source": "LILACS_chatbot_skill",
"utterances": [
"bump chat to active skill list"]}))
while i < 60 * self.TIMEOUT:
i += 1
sleep(1)
i = 0
def make_bump_thread(self):
timer_thread = Thread(target=self.ping)
timer_thread.setDaemon(True)
timer_thread.start()
def build_intents(self):
# build intents
deactivate_intent = IntentBuilder("DeactivateChatbotIntent") \
.require("deactivateChatBotKeyword").build()
activate_intent=IntentBuilder("ActivateChatbotIntent") \
.require("activateChatBotKeyword").build()
bump_intent = IntentBuilder("BumpChatBotSkillIntent"). \
require("bumpChatBotKeyword").build()
# register intents
self.register_intent(deactivate_intent, self.handle_deactivate_intent)
self.register_intent(activate_intent, self.handle_activate_intent)
self.register_intent(bump_intent, self.handle_set_on_top_active_list())
def handle_set_on_top_active_list(self):
# dummy intent just to bump curiosity skill to top of active skill list
# called on a timer in order to always use converse method
pass
def handle_deactivate_intent(self, message):
self.active = False
self.speak_dialog("chatbot_off")
def handle_activate_intent(self, message):
self.active = True
self.speak_dialog("chatbot_on")
def stop(self):
self.handle_deactivate_intent("global stop")
def converse(self, transcript, lang="en-us"):
# parse 1st utterance for entitys
if self.active and "bump chat" not in transcript[0] and "bump curiosity" not in transcript[0]:
nodes, parents, synonims = self.parser.tag_from_dbpedia(transcript[0])
self.log.info("nodes: " + str(nodes))
self.log.info("parents: " + str(parents))
self.log.info("synonims: " + str(synonims))
# get concept net , talk
possible_responses = []
for node in nodes:
try:
dict = self.service.adquire(node, "concept net")
usages = dict["concept net"]["surfaceText"]
for usage in usages:
possible_responses.append(usage.replace("[", "").replace("]", ""))
except:
self.log.info("could not get reply for node " + node)
try:
# say something random
reply = random.choice(possible_responses)
self.speak(reply)
return True
except:
self.log.error("Could not get chatbot response for: " + transcript[0])
# dont know what to say
# TODO ask user a question and play du,mb
return False
# tell intent skill you did not handle intent
return False
def <|fim_middle|>():
return LILACSChatbotSkill()<|fim▁end|> | create_skill |
<|file_name|>test_run_info.py<|end_file_name|><|fim▁begin|>from unittest import TestCase
from micall.drivers.run_info import RunInfo
from micall.drivers.sample import Sample
from micall.drivers.sample_group import SampleGroup
class RunInfoTest(TestCase):
def test_get_all_samples(self):
expected_fastq_paths = ['1a_R1_001.fastq',
'1b_R1_001.fastq',<|fim▁hole|> run_info = RunInfo(
sample_groups=[SampleGroup(Sample(fastq1='1a_R1_001.fastq'),
Sample(fastq1='1b_R1_001.fastq')),
SampleGroup(Sample(fastq1='2_R1_001.fastq'))])
fastq_paths = [sample.fastq1 for sample in run_info.get_all_samples()]
self.assertEqual(expected_fastq_paths, fastq_paths)<|fim▁end|> | '2_R1_001.fastq']
|
<|file_name|>test_run_info.py<|end_file_name|><|fim▁begin|>from unittest import TestCase
from micall.drivers.run_info import RunInfo
from micall.drivers.sample import Sample
from micall.drivers.sample_group import SampleGroup
class RunInfoTest(TestCase):
<|fim_middle|>
<|fim▁end|> | def test_get_all_samples(self):
expected_fastq_paths = ['1a_R1_001.fastq',
'1b_R1_001.fastq',
'2_R1_001.fastq']
run_info = RunInfo(
sample_groups=[SampleGroup(Sample(fastq1='1a_R1_001.fastq'),
Sample(fastq1='1b_R1_001.fastq')),
SampleGroup(Sample(fastq1='2_R1_001.fastq'))])
fastq_paths = [sample.fastq1 for sample in run_info.get_all_samples()]
self.assertEqual(expected_fastq_paths, fastq_paths) |
<|file_name|>test_run_info.py<|end_file_name|><|fim▁begin|>from unittest import TestCase
from micall.drivers.run_info import RunInfo
from micall.drivers.sample import Sample
from micall.drivers.sample_group import SampleGroup
class RunInfoTest(TestCase):
def test_get_all_samples(self):
<|fim_middle|>
<|fim▁end|> | expected_fastq_paths = ['1a_R1_001.fastq',
'1b_R1_001.fastq',
'2_R1_001.fastq']
run_info = RunInfo(
sample_groups=[SampleGroup(Sample(fastq1='1a_R1_001.fastq'),
Sample(fastq1='1b_R1_001.fastq')),
SampleGroup(Sample(fastq1='2_R1_001.fastq'))])
fastq_paths = [sample.fastq1 for sample in run_info.get_all_samples()]
self.assertEqual(expected_fastq_paths, fastq_paths) |
<|file_name|>test_run_info.py<|end_file_name|><|fim▁begin|>from unittest import TestCase
from micall.drivers.run_info import RunInfo
from micall.drivers.sample import Sample
from micall.drivers.sample_group import SampleGroup
class RunInfoTest(TestCase):
def <|fim_middle|>(self):
expected_fastq_paths = ['1a_R1_001.fastq',
'1b_R1_001.fastq',
'2_R1_001.fastq']
run_info = RunInfo(
sample_groups=[SampleGroup(Sample(fastq1='1a_R1_001.fastq'),
Sample(fastq1='1b_R1_001.fastq')),
SampleGroup(Sample(fastq1='2_R1_001.fastq'))])
fastq_paths = [sample.fastq1 for sample in run_info.get_all_samples()]
self.assertEqual(expected_fastq_paths, fastq_paths)
<|fim▁end|> | test_get_all_samples |
<|file_name|>winprocess.py<|end_file_name|><|fim▁begin|>"""
Windows Process Control
winprocess.run launches a child process and returns the exit code.
Optionally, it can:
redirect stdin, stdout & stderr to files
run the command as another user
limit the process's running time
control the process window (location, size, window state, desktop)
Works on Windows NT, 2000 & XP. Requires Mark Hammond's win32
extensions.
This code is free for any purpose, with no warranty of any kind.
-- John B. Dell'Aquila <[email protected]>
"""
import win32api, win32process, win32security
import win32event, win32con, msvcrt, win32gui
def logonUser(loginString):
"""
Login as specified user and return handle.
loginString: 'Domain\nUser\nPassword'; for local
login use . or empty string as domain
e.g. '.\nadministrator\nsecret_password'
"""
domain, user, passwd = loginString.split('\n')
return win32security.LogonUser(
user,
domain,<|fim▁hole|> passwd,
win32con.LOGON32_LOGON_INTERACTIVE,
win32con.LOGON32_PROVIDER_DEFAULT
)
class Process:
"""
A Windows process.
"""
def __init__(self, cmd, login=None,
hStdin=None, hStdout=None, hStderr=None,
show=1, xy=None, xySize=None,
desktop=None):
"""
Create a Windows process.
cmd: command to run
login: run as user 'Domain\nUser\nPassword'
hStdin, hStdout, hStderr:
handles for process I/O; default is caller's stdin,
stdout & stderr
show: wShowWindow (0=SW_HIDE, 1=SW_NORMAL, ...)
xy: window offset (x, y) of upper left corner in pixels
xySize: window size (width, height) in pixels
desktop: lpDesktop - name of desktop e.g. 'winsta0\\default'
None = inherit current desktop
'' = create new desktop if necessary
User calling login requires additional privileges:
Act as part of the operating system [not needed on Windows XP]
Increase quotas
Replace a process level token
Login string must EITHER be an administrator's account
(ordinary user can't access current desktop - see Microsoft
Q165194) OR use desktop='' to run another desktop invisibly
(may be very slow to startup & finalize).
"""
si = win32process.STARTUPINFO()
si.dwFlags = (win32con.STARTF_USESTDHANDLES ^
win32con.STARTF_USESHOWWINDOW)
if hStdin is None:
si.hStdInput = win32api.GetStdHandle(win32api.STD_INPUT_HANDLE)
else:
si.hStdInput = hStdin
if hStdout is None:
si.hStdOutput = win32api.GetStdHandle(win32api.STD_OUTPUT_HANDLE)
else:
si.hStdOutput = hStdout
if hStderr is None:
si.hStdError = win32api.GetStdHandle(win32api.STD_ERROR_HANDLE)
else:
si.hStdError = hStderr
si.wShowWindow = show
if xy is not None:
si.dwX, si.dwY = xy
si.dwFlags ^= win32con.STARTF_USEPOSITION
if xySize is not None:
si.dwXSize, si.dwYSize = xySize
si.dwFlags ^= win32con.STARTF_USESIZE
if desktop is not None:
si.lpDesktop = desktop
procArgs = (None, # appName
cmd, # commandLine
None, # processAttributes
None, # threadAttributes
1, # bInheritHandles
win32process.CREATE_NEW_CONSOLE, # dwCreationFlags
None, # newEnvironment
None, # currentDirectory
si) # startupinfo
if login is not None:
hUser = logonUser(login)
win32security.ImpersonateLoggedOnUser(hUser)
procHandles = win32process.CreateProcessAsUser(hUser, *procArgs)
win32security.RevertToSelf()
else:
procHandles = win32process.CreateProcess(*procArgs)
self.hProcess, self.hThread, self.PId, self.TId = procHandles
def wait(self, mSec=None):
"""
Wait for process to finish or for specified number of
milliseconds to elapse.
"""
if mSec is None:
mSec = win32event.INFINITE
return win32event.WaitForSingleObject(self.hProcess, mSec)
def kill(self, gracePeriod=5000):
"""
Kill process. Try for an orderly shutdown via WM_CLOSE. If
still running after gracePeriod (5 sec. default), terminate.
"""
win32gui.EnumWindows(self.__close__, 0)
if self.wait(gracePeriod) != win32event.WAIT_OBJECT_0:
win32process.TerminateProcess(self.hProcess, 0)
win32api.Sleep(100) # wait for resources to be released
def __close__(self, hwnd, dummy):
"""
EnumWindows callback - sends WM_CLOSE to any window
owned by this process.
"""
TId, PId = win32process.GetWindowThreadProcessId(hwnd)
if PId == self.PId:
win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0)
def exitCode(self):
"""
Return process exit code.
"""
return win32process.GetExitCodeProcess(self.hProcess)
def run(cmd, mSec=None, stdin=None, stdout=None, stderr=None, **kw):
"""
Run cmd as a child process and return exit code.
mSec: terminate cmd after specified number of milliseconds
stdin, stdout, stderr:
file objects for child I/O (use hStdin etc. to attach
handles instead of files); default is caller's stdin,
stdout & stderr;
kw: see Process.__init__ for more keyword options
"""
if stdin is not None:
kw['hStdin'] = msvcrt.get_osfhandle(stdin.fileno())
if stdout is not None:
kw['hStdout'] = msvcrt.get_osfhandle(stdout.fileno())
if stderr is not None:
kw['hStderr'] = msvcrt.get_osfhandle(stderr.fileno())
child = Process(cmd, **kw)
if child.wait(mSec) != win32event.WAIT_OBJECT_0:
child.kill()
raise WindowsError, 'process timeout exceeded'
return child.exitCode()
if __name__ == '__main__':
# Pipe commands to a shell and display the output in notepad
print 'Testing winprocess.py...'
import tempfile
timeoutSeconds = 15
cmdString = """\
REM Test of winprocess.py piping commands to a shell.\r
REM This window will close in %d seconds.\r
vol\r
net user\r
_this_is_a_test_of_stderr_\r
""" % timeoutSeconds
cmd, out = tempfile.TemporaryFile(), tempfile.TemporaryFile()
cmd.write(cmdString)
cmd.seek(0)
print 'CMD.EXE exit code:', run('cmd.exe', show=0, stdin=cmd,
stdout=out, stderr=out)
cmd.close()
print 'NOTEPAD exit code:', run('notepad.exe %s' % out.file.name,
show=win32con.SW_MAXIMIZE,
mSec=timeoutSeconds*1000)
out.close()<|fim▁end|> | |
<|file_name|>winprocess.py<|end_file_name|><|fim▁begin|>"""
Windows Process Control
winprocess.run launches a child process and returns the exit code.
Optionally, it can:
redirect stdin, stdout & stderr to files
run the command as another user
limit the process's running time
control the process window (location, size, window state, desktop)
Works on Windows NT, 2000 & XP. Requires Mark Hammond's win32
extensions.
This code is free for any purpose, with no warranty of any kind.
-- John B. Dell'Aquila <[email protected]>
"""
import win32api, win32process, win32security
import win32event, win32con, msvcrt, win32gui
def logonUser(loginString):
<|fim_middle|>
class Process:
"""
A Windows process.
"""
def __init__(self, cmd, login=None,
hStdin=None, hStdout=None, hStderr=None,
show=1, xy=None, xySize=None,
desktop=None):
"""
Create a Windows process.
cmd: command to run
login: run as user 'Domain\nUser\nPassword'
hStdin, hStdout, hStderr:
handles for process I/O; default is caller's stdin,
stdout & stderr
show: wShowWindow (0=SW_HIDE, 1=SW_NORMAL, ...)
xy: window offset (x, y) of upper left corner in pixels
xySize: window size (width, height) in pixels
desktop: lpDesktop - name of desktop e.g. 'winsta0\\default'
None = inherit current desktop
'' = create new desktop if necessary
User calling login requires additional privileges:
Act as part of the operating system [not needed on Windows XP]
Increase quotas
Replace a process level token
Login string must EITHER be an administrator's account
(ordinary user can't access current desktop - see Microsoft
Q165194) OR use desktop='' to run another desktop invisibly
(may be very slow to startup & finalize).
"""
si = win32process.STARTUPINFO()
si.dwFlags = (win32con.STARTF_USESTDHANDLES ^
win32con.STARTF_USESHOWWINDOW)
if hStdin is None:
si.hStdInput = win32api.GetStdHandle(win32api.STD_INPUT_HANDLE)
else:
si.hStdInput = hStdin
if hStdout is None:
si.hStdOutput = win32api.GetStdHandle(win32api.STD_OUTPUT_HANDLE)
else:
si.hStdOutput = hStdout
if hStderr is None:
si.hStdError = win32api.GetStdHandle(win32api.STD_ERROR_HANDLE)
else:
si.hStdError = hStderr
si.wShowWindow = show
if xy is not None:
si.dwX, si.dwY = xy
si.dwFlags ^= win32con.STARTF_USEPOSITION
if xySize is not None:
si.dwXSize, si.dwYSize = xySize
si.dwFlags ^= win32con.STARTF_USESIZE
if desktop is not None:
si.lpDesktop = desktop
procArgs = (None, # appName
cmd, # commandLine
None, # processAttributes
None, # threadAttributes
1, # bInheritHandles
win32process.CREATE_NEW_CONSOLE, # dwCreationFlags
None, # newEnvironment
None, # currentDirectory
si) # startupinfo
if login is not None:
hUser = logonUser(login)
win32security.ImpersonateLoggedOnUser(hUser)
procHandles = win32process.CreateProcessAsUser(hUser, *procArgs)
win32security.RevertToSelf()
else:
procHandles = win32process.CreateProcess(*procArgs)
self.hProcess, self.hThread, self.PId, self.TId = procHandles
def wait(self, mSec=None):
"""
Wait for process to finish or for specified number of
milliseconds to elapse.
"""
if mSec is None:
mSec = win32event.INFINITE
return win32event.WaitForSingleObject(self.hProcess, mSec)
def kill(self, gracePeriod=5000):
"""
Kill process. Try for an orderly shutdown via WM_CLOSE. If
still running after gracePeriod (5 sec. default), terminate.
"""
win32gui.EnumWindows(self.__close__, 0)
if self.wait(gracePeriod) != win32event.WAIT_OBJECT_0:
win32process.TerminateProcess(self.hProcess, 0)
win32api.Sleep(100) # wait for resources to be released
def __close__(self, hwnd, dummy):
"""
EnumWindows callback - sends WM_CLOSE to any window
owned by this process.
"""
TId, PId = win32process.GetWindowThreadProcessId(hwnd)
if PId == self.PId:
win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0)
def exitCode(self):
"""
Return process exit code.
"""
return win32process.GetExitCodeProcess(self.hProcess)
def run(cmd, mSec=None, stdin=None, stdout=None, stderr=None, **kw):
"""
Run cmd as a child process and return exit code.
mSec: terminate cmd after specified number of milliseconds
stdin, stdout, stderr:
file objects for child I/O (use hStdin etc. to attach
handles instead of files); default is caller's stdin,
stdout & stderr;
kw: see Process.__init__ for more keyword options
"""
if stdin is not None:
kw['hStdin'] = msvcrt.get_osfhandle(stdin.fileno())
if stdout is not None:
kw['hStdout'] = msvcrt.get_osfhandle(stdout.fileno())
if stderr is not None:
kw['hStderr'] = msvcrt.get_osfhandle(stderr.fileno())
child = Process(cmd, **kw)
if child.wait(mSec) != win32event.WAIT_OBJECT_0:
child.kill()
raise WindowsError, 'process timeout exceeded'
return child.exitCode()
if __name__ == '__main__':
# Pipe commands to a shell and display the output in notepad
print 'Testing winprocess.py...'
import tempfile
timeoutSeconds = 15
cmdString = """\
REM Test of winprocess.py piping commands to a shell.\r
REM This window will close in %d seconds.\r
vol\r
net user\r
_this_is_a_test_of_stderr_\r
""" % timeoutSeconds
cmd, out = tempfile.TemporaryFile(), tempfile.TemporaryFile()
cmd.write(cmdString)
cmd.seek(0)
print 'CMD.EXE exit code:', run('cmd.exe', show=0, stdin=cmd,
stdout=out, stderr=out)
cmd.close()
print 'NOTEPAD exit code:', run('notepad.exe %s' % out.file.name,
show=win32con.SW_MAXIMIZE,
mSec=timeoutSeconds*1000)
out.close()
<|fim▁end|> | """
Login as specified user and return handle.
loginString: 'Domain\nUser\nPassword'; for local
login use . or empty string as domain
e.g. '.\nadministrator\nsecret_password'
"""
domain, user, passwd = loginString.split('\n')
return win32security.LogonUser(
user,
domain,
passwd,
win32con.LOGON32_LOGON_INTERACTIVE,
win32con.LOGON32_PROVIDER_DEFAULT
) |
<|file_name|>winprocess.py<|end_file_name|><|fim▁begin|>"""
Windows Process Control
winprocess.run launches a child process and returns the exit code.
Optionally, it can:
redirect stdin, stdout & stderr to files
run the command as another user
limit the process's running time
control the process window (location, size, window state, desktop)
Works on Windows NT, 2000 & XP. Requires Mark Hammond's win32
extensions.
This code is free for any purpose, with no warranty of any kind.
-- John B. Dell'Aquila <[email protected]>
"""
import win32api, win32process, win32security
import win32event, win32con, msvcrt, win32gui
def logonUser(loginString):
"""
Login as specified user and return handle.
loginString: 'Domain\nUser\nPassword'; for local
login use . or empty string as domain
e.g. '.\nadministrator\nsecret_password'
"""
domain, user, passwd = loginString.split('\n')
return win32security.LogonUser(
user,
domain,
passwd,
win32con.LOGON32_LOGON_INTERACTIVE,
win32con.LOGON32_PROVIDER_DEFAULT
)
class Process:
<|fim_middle|>
def run(cmd, mSec=None, stdin=None, stdout=None, stderr=None, **kw):
"""
Run cmd as a child process and return exit code.
mSec: terminate cmd after specified number of milliseconds
stdin, stdout, stderr:
file objects for child I/O (use hStdin etc. to attach
handles instead of files); default is caller's stdin,
stdout & stderr;
kw: see Process.__init__ for more keyword options
"""
if stdin is not None:
kw['hStdin'] = msvcrt.get_osfhandle(stdin.fileno())
if stdout is not None:
kw['hStdout'] = msvcrt.get_osfhandle(stdout.fileno())
if stderr is not None:
kw['hStderr'] = msvcrt.get_osfhandle(stderr.fileno())
child = Process(cmd, **kw)
if child.wait(mSec) != win32event.WAIT_OBJECT_0:
child.kill()
raise WindowsError, 'process timeout exceeded'
return child.exitCode()
if __name__ == '__main__':
# Pipe commands to a shell and display the output in notepad
print 'Testing winprocess.py...'
import tempfile
timeoutSeconds = 15
cmdString = """\
REM Test of winprocess.py piping commands to a shell.\r
REM This window will close in %d seconds.\r
vol\r
net user\r
_this_is_a_test_of_stderr_\r
""" % timeoutSeconds
cmd, out = tempfile.TemporaryFile(), tempfile.TemporaryFile()
cmd.write(cmdString)
cmd.seek(0)
print 'CMD.EXE exit code:', run('cmd.exe', show=0, stdin=cmd,
stdout=out, stderr=out)
cmd.close()
print 'NOTEPAD exit code:', run('notepad.exe %s' % out.file.name,
show=win32con.SW_MAXIMIZE,
mSec=timeoutSeconds*1000)
out.close()
<|fim▁end|> | """
A Windows process.
"""
def __init__(self, cmd, login=None,
hStdin=None, hStdout=None, hStderr=None,
show=1, xy=None, xySize=None,
desktop=None):
"""
Create a Windows process.
cmd: command to run
login: run as user 'Domain\nUser\nPassword'
hStdin, hStdout, hStderr:
handles for process I/O; default is caller's stdin,
stdout & stderr
show: wShowWindow (0=SW_HIDE, 1=SW_NORMAL, ...)
xy: window offset (x, y) of upper left corner in pixels
xySize: window size (width, height) in pixels
desktop: lpDesktop - name of desktop e.g. 'winsta0\\default'
None = inherit current desktop
'' = create new desktop if necessary
User calling login requires additional privileges:
Act as part of the operating system [not needed on Windows XP]
Increase quotas
Replace a process level token
Login string must EITHER be an administrator's account
(ordinary user can't access current desktop - see Microsoft
Q165194) OR use desktop='' to run another desktop invisibly
(may be very slow to startup & finalize).
"""
si = win32process.STARTUPINFO()
si.dwFlags = (win32con.STARTF_USESTDHANDLES ^
win32con.STARTF_USESHOWWINDOW)
if hStdin is None:
si.hStdInput = win32api.GetStdHandle(win32api.STD_INPUT_HANDLE)
else:
si.hStdInput = hStdin
if hStdout is None:
si.hStdOutput = win32api.GetStdHandle(win32api.STD_OUTPUT_HANDLE)
else:
si.hStdOutput = hStdout
if hStderr is None:
si.hStdError = win32api.GetStdHandle(win32api.STD_ERROR_HANDLE)
else:
si.hStdError = hStderr
si.wShowWindow = show
if xy is not None:
si.dwX, si.dwY = xy
si.dwFlags ^= win32con.STARTF_USEPOSITION
if xySize is not None:
si.dwXSize, si.dwYSize = xySize
si.dwFlags ^= win32con.STARTF_USESIZE
if desktop is not None:
si.lpDesktop = desktop
procArgs = (None, # appName
cmd, # commandLine
None, # processAttributes
None, # threadAttributes
1, # bInheritHandles
win32process.CREATE_NEW_CONSOLE, # dwCreationFlags
None, # newEnvironment
None, # currentDirectory
si) # startupinfo
if login is not None:
hUser = logonUser(login)
win32security.ImpersonateLoggedOnUser(hUser)
procHandles = win32process.CreateProcessAsUser(hUser, *procArgs)
win32security.RevertToSelf()
else:
procHandles = win32process.CreateProcess(*procArgs)
self.hProcess, self.hThread, self.PId, self.TId = procHandles
def wait(self, mSec=None):
"""
Wait for process to finish or for specified number of
milliseconds to elapse.
"""
if mSec is None:
mSec = win32event.INFINITE
return win32event.WaitForSingleObject(self.hProcess, mSec)
def kill(self, gracePeriod=5000):
"""
Kill process. Try for an orderly shutdown via WM_CLOSE. If
still running after gracePeriod (5 sec. default), terminate.
"""
win32gui.EnumWindows(self.__close__, 0)
if self.wait(gracePeriod) != win32event.WAIT_OBJECT_0:
win32process.TerminateProcess(self.hProcess, 0)
win32api.Sleep(100) # wait for resources to be released
def __close__(self, hwnd, dummy):
"""
EnumWindows callback - sends WM_CLOSE to any window
owned by this process.
"""
TId, PId = win32process.GetWindowThreadProcessId(hwnd)
if PId == self.PId:
win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0)
def exitCode(self):
"""
Return process exit code.
"""
return win32process.GetExitCodeProcess(self.hProcess) |
<|file_name|>winprocess.py<|end_file_name|><|fim▁begin|>"""
Windows Process Control
winprocess.run launches a child process and returns the exit code.
Optionally, it can:
redirect stdin, stdout & stderr to files
run the command as another user
limit the process's running time
control the process window (location, size, window state, desktop)
Works on Windows NT, 2000 & XP. Requires Mark Hammond's win32
extensions.
This code is free for any purpose, with no warranty of any kind.
-- John B. Dell'Aquila <[email protected]>
"""
import win32api, win32process, win32security
import win32event, win32con, msvcrt, win32gui
def logonUser(loginString):
"""
Login as specified user and return handle.
loginString: 'Domain\nUser\nPassword'; for local
login use . or empty string as domain
e.g. '.\nadministrator\nsecret_password'
"""
domain, user, passwd = loginString.split('\n')
return win32security.LogonUser(
user,
domain,
passwd,
win32con.LOGON32_LOGON_INTERACTIVE,
win32con.LOGON32_PROVIDER_DEFAULT
)
class Process:
"""
A Windows process.
"""
def __init__(self, cmd, login=None,
hStdin=None, hStdout=None, hStderr=None,
show=1, xy=None, xySize=None,
desktop=None):
<|fim_middle|>
def wait(self, mSec=None):
"""
Wait for process to finish or for specified number of
milliseconds to elapse.
"""
if mSec is None:
mSec = win32event.INFINITE
return win32event.WaitForSingleObject(self.hProcess, mSec)
def kill(self, gracePeriod=5000):
"""
Kill process. Try for an orderly shutdown via WM_CLOSE. If
still running after gracePeriod (5 sec. default), terminate.
"""
win32gui.EnumWindows(self.__close__, 0)
if self.wait(gracePeriod) != win32event.WAIT_OBJECT_0:
win32process.TerminateProcess(self.hProcess, 0)
win32api.Sleep(100) # wait for resources to be released
def __close__(self, hwnd, dummy):
"""
EnumWindows callback - sends WM_CLOSE to any window
owned by this process.
"""
TId, PId = win32process.GetWindowThreadProcessId(hwnd)
if PId == self.PId:
win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0)
def exitCode(self):
"""
Return process exit code.
"""
return win32process.GetExitCodeProcess(self.hProcess)
def run(cmd, mSec=None, stdin=None, stdout=None, stderr=None, **kw):
"""
Run cmd as a child process and return exit code.
mSec: terminate cmd after specified number of milliseconds
stdin, stdout, stderr:
file objects for child I/O (use hStdin etc. to attach
handles instead of files); default is caller's stdin,
stdout & stderr;
kw: see Process.__init__ for more keyword options
"""
if stdin is not None:
kw['hStdin'] = msvcrt.get_osfhandle(stdin.fileno())
if stdout is not None:
kw['hStdout'] = msvcrt.get_osfhandle(stdout.fileno())
if stderr is not None:
kw['hStderr'] = msvcrt.get_osfhandle(stderr.fileno())
child = Process(cmd, **kw)
if child.wait(mSec) != win32event.WAIT_OBJECT_0:
child.kill()
raise WindowsError, 'process timeout exceeded'
return child.exitCode()
if __name__ == '__main__':
# Pipe commands to a shell and display the output in notepad
print 'Testing winprocess.py...'
import tempfile
timeoutSeconds = 15
cmdString = """\
REM Test of winprocess.py piping commands to a shell.\r
REM This window will close in %d seconds.\r
vol\r
net user\r
_this_is_a_test_of_stderr_\r
""" % timeoutSeconds
cmd, out = tempfile.TemporaryFile(), tempfile.TemporaryFile()
cmd.write(cmdString)
cmd.seek(0)
print 'CMD.EXE exit code:', run('cmd.exe', show=0, stdin=cmd,
stdout=out, stderr=out)
cmd.close()
print 'NOTEPAD exit code:', run('notepad.exe %s' % out.file.name,
show=win32con.SW_MAXIMIZE,
mSec=timeoutSeconds*1000)
out.close()
<|fim▁end|> | """
Create a Windows process.
cmd: command to run
login: run as user 'Domain\nUser\nPassword'
hStdin, hStdout, hStderr:
handles for process I/O; default is caller's stdin,
stdout & stderr
show: wShowWindow (0=SW_HIDE, 1=SW_NORMAL, ...)
xy: window offset (x, y) of upper left corner in pixels
xySize: window size (width, height) in pixels
desktop: lpDesktop - name of desktop e.g. 'winsta0\\default'
None = inherit current desktop
'' = create new desktop if necessary
User calling login requires additional privileges:
Act as part of the operating system [not needed on Windows XP]
Increase quotas
Replace a process level token
Login string must EITHER be an administrator's account
(ordinary user can't access current desktop - see Microsoft
Q165194) OR use desktop='' to run another desktop invisibly
(may be very slow to startup & finalize).
"""
si = win32process.STARTUPINFO()
si.dwFlags = (win32con.STARTF_USESTDHANDLES ^
win32con.STARTF_USESHOWWINDOW)
if hStdin is None:
si.hStdInput = win32api.GetStdHandle(win32api.STD_INPUT_HANDLE)
else:
si.hStdInput = hStdin
if hStdout is None:
si.hStdOutput = win32api.GetStdHandle(win32api.STD_OUTPUT_HANDLE)
else:
si.hStdOutput = hStdout
if hStderr is None:
si.hStdError = win32api.GetStdHandle(win32api.STD_ERROR_HANDLE)
else:
si.hStdError = hStderr
si.wShowWindow = show
if xy is not None:
si.dwX, si.dwY = xy
si.dwFlags ^= win32con.STARTF_USEPOSITION
if xySize is not None:
si.dwXSize, si.dwYSize = xySize
si.dwFlags ^= win32con.STARTF_USESIZE
if desktop is not None:
si.lpDesktop = desktop
procArgs = (None, # appName
cmd, # commandLine
None, # processAttributes
None, # threadAttributes
1, # bInheritHandles
win32process.CREATE_NEW_CONSOLE, # dwCreationFlags
None, # newEnvironment
None, # currentDirectory
si) # startupinfo
if login is not None:
hUser = logonUser(login)
win32security.ImpersonateLoggedOnUser(hUser)
procHandles = win32process.CreateProcessAsUser(hUser, *procArgs)
win32security.RevertToSelf()
else:
procHandles = win32process.CreateProcess(*procArgs)
self.hProcess, self.hThread, self.PId, self.TId = procHandles |
<|file_name|>winprocess.py<|end_file_name|><|fim▁begin|>"""
Windows Process Control
winprocess.run launches a child process and returns the exit code.
Optionally, it can:
redirect stdin, stdout & stderr to files
run the command as another user
limit the process's running time
control the process window (location, size, window state, desktop)
Works on Windows NT, 2000 & XP. Requires Mark Hammond's win32
extensions.
This code is free for any purpose, with no warranty of any kind.
-- John B. Dell'Aquila <[email protected]>
"""
import win32api, win32process, win32security
import win32event, win32con, msvcrt, win32gui
def logonUser(loginString):
"""
Login as specified user and return handle.
loginString: 'Domain\nUser\nPassword'; for local
login use . or empty string as domain
e.g. '.\nadministrator\nsecret_password'
"""
domain, user, passwd = loginString.split('\n')
return win32security.LogonUser(
user,
domain,
passwd,
win32con.LOGON32_LOGON_INTERACTIVE,
win32con.LOGON32_PROVIDER_DEFAULT
)
class Process:
"""
A Windows process.
"""
def __init__(self, cmd, login=None,
hStdin=None, hStdout=None, hStderr=None,
show=1, xy=None, xySize=None,
desktop=None):
"""
Create a Windows process.
cmd: command to run
login: run as user 'Domain\nUser\nPassword'
hStdin, hStdout, hStderr:
handles for process I/O; default is caller's stdin,
stdout & stderr
show: wShowWindow (0=SW_HIDE, 1=SW_NORMAL, ...)
xy: window offset (x, y) of upper left corner in pixels
xySize: window size (width, height) in pixels
desktop: lpDesktop - name of desktop e.g. 'winsta0\\default'
None = inherit current desktop
'' = create new desktop if necessary
User calling login requires additional privileges:
Act as part of the operating system [not needed on Windows XP]
Increase quotas
Replace a process level token
Login string must EITHER be an administrator's account
(ordinary user can't access current desktop - see Microsoft
Q165194) OR use desktop='' to run another desktop invisibly
(may be very slow to startup & finalize).
"""
si = win32process.STARTUPINFO()
si.dwFlags = (win32con.STARTF_USESTDHANDLES ^
win32con.STARTF_USESHOWWINDOW)
if hStdin is None:
si.hStdInput = win32api.GetStdHandle(win32api.STD_INPUT_HANDLE)
else:
si.hStdInput = hStdin
if hStdout is None:
si.hStdOutput = win32api.GetStdHandle(win32api.STD_OUTPUT_HANDLE)
else:
si.hStdOutput = hStdout
if hStderr is None:
si.hStdError = win32api.GetStdHandle(win32api.STD_ERROR_HANDLE)
else:
si.hStdError = hStderr
si.wShowWindow = show
if xy is not None:
si.dwX, si.dwY = xy
si.dwFlags ^= win32con.STARTF_USEPOSITION
if xySize is not None:
si.dwXSize, si.dwYSize = xySize
si.dwFlags ^= win32con.STARTF_USESIZE
if desktop is not None:
si.lpDesktop = desktop
procArgs = (None, # appName
cmd, # commandLine
None, # processAttributes
None, # threadAttributes
1, # bInheritHandles
win32process.CREATE_NEW_CONSOLE, # dwCreationFlags
None, # newEnvironment
None, # currentDirectory
si) # startupinfo
if login is not None:
hUser = logonUser(login)
win32security.ImpersonateLoggedOnUser(hUser)
procHandles = win32process.CreateProcessAsUser(hUser, *procArgs)
win32security.RevertToSelf()
else:
procHandles = win32process.CreateProcess(*procArgs)
self.hProcess, self.hThread, self.PId, self.TId = procHandles
def wait(self, mSec=None):
<|fim_middle|>
def kill(self, gracePeriod=5000):
"""
Kill process. Try for an orderly shutdown via WM_CLOSE. If
still running after gracePeriod (5 sec. default), terminate.
"""
win32gui.EnumWindows(self.__close__, 0)
if self.wait(gracePeriod) != win32event.WAIT_OBJECT_0:
win32process.TerminateProcess(self.hProcess, 0)
win32api.Sleep(100) # wait for resources to be released
def __close__(self, hwnd, dummy):
"""
EnumWindows callback - sends WM_CLOSE to any window
owned by this process.
"""
TId, PId = win32process.GetWindowThreadProcessId(hwnd)
if PId == self.PId:
win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0)
def exitCode(self):
"""
Return process exit code.
"""
return win32process.GetExitCodeProcess(self.hProcess)
def run(cmd, mSec=None, stdin=None, stdout=None, stderr=None, **kw):
"""
Run cmd as a child process and return exit code.
mSec: terminate cmd after specified number of milliseconds
stdin, stdout, stderr:
file objects for child I/O (use hStdin etc. to attach
handles instead of files); default is caller's stdin,
stdout & stderr;
kw: see Process.__init__ for more keyword options
"""
if stdin is not None:
kw['hStdin'] = msvcrt.get_osfhandle(stdin.fileno())
if stdout is not None:
kw['hStdout'] = msvcrt.get_osfhandle(stdout.fileno())
if stderr is not None:
kw['hStderr'] = msvcrt.get_osfhandle(stderr.fileno())
child = Process(cmd, **kw)
if child.wait(mSec) != win32event.WAIT_OBJECT_0:
child.kill()
raise WindowsError, 'process timeout exceeded'
return child.exitCode()
if __name__ == '__main__':
# Pipe commands to a shell and display the output in notepad
print 'Testing winprocess.py...'
import tempfile
timeoutSeconds = 15
cmdString = """\
REM Test of winprocess.py piping commands to a shell.\r
REM This window will close in %d seconds.\r
vol\r
net user\r
_this_is_a_test_of_stderr_\r
""" % timeoutSeconds
cmd, out = tempfile.TemporaryFile(), tempfile.TemporaryFile()
cmd.write(cmdString)
cmd.seek(0)
print 'CMD.EXE exit code:', run('cmd.exe', show=0, stdin=cmd,
stdout=out, stderr=out)
cmd.close()
print 'NOTEPAD exit code:', run('notepad.exe %s' % out.file.name,
show=win32con.SW_MAXIMIZE,
mSec=timeoutSeconds*1000)
out.close()
<|fim▁end|> | """
Wait for process to finish or for specified number of
milliseconds to elapse.
"""
if mSec is None:
mSec = win32event.INFINITE
return win32event.WaitForSingleObject(self.hProcess, mSec) |
<|file_name|>winprocess.py<|end_file_name|><|fim▁begin|>"""
Windows Process Control
winprocess.run launches a child process and returns the exit code.
Optionally, it can:
redirect stdin, stdout & stderr to files
run the command as another user
limit the process's running time
control the process window (location, size, window state, desktop)
Works on Windows NT, 2000 & XP. Requires Mark Hammond's win32
extensions.
This code is free for any purpose, with no warranty of any kind.
-- John B. Dell'Aquila <[email protected]>
"""
import win32api, win32process, win32security
import win32event, win32con, msvcrt, win32gui
def logonUser(loginString):
"""
Login as specified user and return handle.
loginString: 'Domain\nUser\nPassword'; for local
login use . or empty string as domain
e.g. '.\nadministrator\nsecret_password'
"""
domain, user, passwd = loginString.split('\n')
return win32security.LogonUser(
user,
domain,
passwd,
win32con.LOGON32_LOGON_INTERACTIVE,
win32con.LOGON32_PROVIDER_DEFAULT
)
class Process:
"""
A Windows process.
"""
def __init__(self, cmd, login=None,
hStdin=None, hStdout=None, hStderr=None,
show=1, xy=None, xySize=None,
desktop=None):
"""
Create a Windows process.
cmd: command to run
login: run as user 'Domain\nUser\nPassword'
hStdin, hStdout, hStderr:
handles for process I/O; default is caller's stdin,
stdout & stderr
show: wShowWindow (0=SW_HIDE, 1=SW_NORMAL, ...)
xy: window offset (x, y) of upper left corner in pixels
xySize: window size (width, height) in pixels
desktop: lpDesktop - name of desktop e.g. 'winsta0\\default'
None = inherit current desktop
'' = create new desktop if necessary
User calling login requires additional privileges:
Act as part of the operating system [not needed on Windows XP]
Increase quotas
Replace a process level token
Login string must EITHER be an administrator's account
(ordinary user can't access current desktop - see Microsoft
Q165194) OR use desktop='' to run another desktop invisibly
(may be very slow to startup & finalize).
"""
si = win32process.STARTUPINFO()
si.dwFlags = (win32con.STARTF_USESTDHANDLES ^
win32con.STARTF_USESHOWWINDOW)
if hStdin is None:
si.hStdInput = win32api.GetStdHandle(win32api.STD_INPUT_HANDLE)
else:
si.hStdInput = hStdin
if hStdout is None:
si.hStdOutput = win32api.GetStdHandle(win32api.STD_OUTPUT_HANDLE)
else:
si.hStdOutput = hStdout
if hStderr is None:
si.hStdError = win32api.GetStdHandle(win32api.STD_ERROR_HANDLE)
else:
si.hStdError = hStderr
si.wShowWindow = show
if xy is not None:
si.dwX, si.dwY = xy
si.dwFlags ^= win32con.STARTF_USEPOSITION
if xySize is not None:
si.dwXSize, si.dwYSize = xySize
si.dwFlags ^= win32con.STARTF_USESIZE
if desktop is not None:
si.lpDesktop = desktop
procArgs = (None, # appName
cmd, # commandLine
None, # processAttributes
None, # threadAttributes
1, # bInheritHandles
win32process.CREATE_NEW_CONSOLE, # dwCreationFlags
None, # newEnvironment
None, # currentDirectory
si) # startupinfo
if login is not None:
hUser = logonUser(login)
win32security.ImpersonateLoggedOnUser(hUser)
procHandles = win32process.CreateProcessAsUser(hUser, *procArgs)
win32security.RevertToSelf()
else:
procHandles = win32process.CreateProcess(*procArgs)
self.hProcess, self.hThread, self.PId, self.TId = procHandles
def wait(self, mSec=None):
"""
Wait for process to finish or for specified number of
milliseconds to elapse.
"""
if mSec is None:
mSec = win32event.INFINITE
return win32event.WaitForSingleObject(self.hProcess, mSec)
def kill(self, gracePeriod=5000):
<|fim_middle|>
def __close__(self, hwnd, dummy):
"""
EnumWindows callback - sends WM_CLOSE to any window
owned by this process.
"""
TId, PId = win32process.GetWindowThreadProcessId(hwnd)
if PId == self.PId:
win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0)
def exitCode(self):
"""
Return process exit code.
"""
return win32process.GetExitCodeProcess(self.hProcess)
def run(cmd, mSec=None, stdin=None, stdout=None, stderr=None, **kw):
"""
Run cmd as a child process and return exit code.
mSec: terminate cmd after specified number of milliseconds
stdin, stdout, stderr:
file objects for child I/O (use hStdin etc. to attach
handles instead of files); default is caller's stdin,
stdout & stderr;
kw: see Process.__init__ for more keyword options
"""
if stdin is not None:
kw['hStdin'] = msvcrt.get_osfhandle(stdin.fileno())
if stdout is not None:
kw['hStdout'] = msvcrt.get_osfhandle(stdout.fileno())
if stderr is not None:
kw['hStderr'] = msvcrt.get_osfhandle(stderr.fileno())
child = Process(cmd, **kw)
if child.wait(mSec) != win32event.WAIT_OBJECT_0:
child.kill()
raise WindowsError, 'process timeout exceeded'
return child.exitCode()
if __name__ == '__main__':
# Pipe commands to a shell and display the output in notepad
print 'Testing winprocess.py...'
import tempfile
timeoutSeconds = 15
cmdString = """\
REM Test of winprocess.py piping commands to a shell.\r
REM This window will close in %d seconds.\r
vol\r
net user\r
_this_is_a_test_of_stderr_\r
""" % timeoutSeconds
cmd, out = tempfile.TemporaryFile(), tempfile.TemporaryFile()
cmd.write(cmdString)
cmd.seek(0)
print 'CMD.EXE exit code:', run('cmd.exe', show=0, stdin=cmd,
stdout=out, stderr=out)
cmd.close()
print 'NOTEPAD exit code:', run('notepad.exe %s' % out.file.name,
show=win32con.SW_MAXIMIZE,
mSec=timeoutSeconds*1000)
out.close()
<|fim▁end|> | """
Kill process. Try for an orderly shutdown via WM_CLOSE. If
still running after gracePeriod (5 sec. default), terminate.
"""
win32gui.EnumWindows(self.__close__, 0)
if self.wait(gracePeriod) != win32event.WAIT_OBJECT_0:
win32process.TerminateProcess(self.hProcess, 0)
win32api.Sleep(100) # wait for resources to be released |
<|file_name|>winprocess.py<|end_file_name|><|fim▁begin|>"""
Windows Process Control
winprocess.run launches a child process and returns the exit code.
Optionally, it can:
redirect stdin, stdout & stderr to files
run the command as another user
limit the process's running time
control the process window (location, size, window state, desktop)
Works on Windows NT, 2000 & XP. Requires Mark Hammond's win32
extensions.
This code is free for any purpose, with no warranty of any kind.
-- John B. Dell'Aquila <[email protected]>
"""
import win32api, win32process, win32security
import win32event, win32con, msvcrt, win32gui
def logonUser(loginString):
"""
Login as specified user and return handle.
loginString: 'Domain\nUser\nPassword'; for local
login use . or empty string as domain
e.g. '.\nadministrator\nsecret_password'
"""
domain, user, passwd = loginString.split('\n')
return win32security.LogonUser(
user,
domain,
passwd,
win32con.LOGON32_LOGON_INTERACTIVE,
win32con.LOGON32_PROVIDER_DEFAULT
)
class Process:
"""
A Windows process.
"""
def __init__(self, cmd, login=None,
hStdin=None, hStdout=None, hStderr=None,
show=1, xy=None, xySize=None,
desktop=None):
"""
Create a Windows process.
cmd: command to run
login: run as user 'Domain\nUser\nPassword'
hStdin, hStdout, hStderr:
handles for process I/O; default is caller's stdin,
stdout & stderr
show: wShowWindow (0=SW_HIDE, 1=SW_NORMAL, ...)
xy: window offset (x, y) of upper left corner in pixels
xySize: window size (width, height) in pixels
desktop: lpDesktop - name of desktop e.g. 'winsta0\\default'
None = inherit current desktop
'' = create new desktop if necessary
User calling login requires additional privileges:
Act as part of the operating system [not needed on Windows XP]
Increase quotas
Replace a process level token
Login string must EITHER be an administrator's account
(ordinary user can't access current desktop - see Microsoft
Q165194) OR use desktop='' to run another desktop invisibly
(may be very slow to startup & finalize).
"""
si = win32process.STARTUPINFO()
si.dwFlags = (win32con.STARTF_USESTDHANDLES ^
win32con.STARTF_USESHOWWINDOW)
if hStdin is None:
si.hStdInput = win32api.GetStdHandle(win32api.STD_INPUT_HANDLE)
else:
si.hStdInput = hStdin
if hStdout is None:
si.hStdOutput = win32api.GetStdHandle(win32api.STD_OUTPUT_HANDLE)
else:
si.hStdOutput = hStdout
if hStderr is None:
si.hStdError = win32api.GetStdHandle(win32api.STD_ERROR_HANDLE)
else:
si.hStdError = hStderr
si.wShowWindow = show
if xy is not None:
si.dwX, si.dwY = xy
si.dwFlags ^= win32con.STARTF_USEPOSITION
if xySize is not None:
si.dwXSize, si.dwYSize = xySize
si.dwFlags ^= win32con.STARTF_USESIZE
if desktop is not None:
si.lpDesktop = desktop
procArgs = (None, # appName
cmd, # commandLine
None, # processAttributes
None, # threadAttributes
1, # bInheritHandles
win32process.CREATE_NEW_CONSOLE, # dwCreationFlags
None, # newEnvironment
None, # currentDirectory
si) # startupinfo
if login is not None:
hUser = logonUser(login)
win32security.ImpersonateLoggedOnUser(hUser)
procHandles = win32process.CreateProcessAsUser(hUser, *procArgs)
win32security.RevertToSelf()
else:
procHandles = win32process.CreateProcess(*procArgs)
self.hProcess, self.hThread, self.PId, self.TId = procHandles
def wait(self, mSec=None):
"""
Wait for process to finish or for specified number of
milliseconds to elapse.
"""
if mSec is None:
mSec = win32event.INFINITE
return win32event.WaitForSingleObject(self.hProcess, mSec)
def kill(self, gracePeriod=5000):
"""
Kill process. Try for an orderly shutdown via WM_CLOSE. If
still running after gracePeriod (5 sec. default), terminate.
"""
win32gui.EnumWindows(self.__close__, 0)
if self.wait(gracePeriod) != win32event.WAIT_OBJECT_0:
win32process.TerminateProcess(self.hProcess, 0)
win32api.Sleep(100) # wait for resources to be released
def __close__(self, hwnd, dummy):
<|fim_middle|>
def exitCode(self):
"""
Return process exit code.
"""
return win32process.GetExitCodeProcess(self.hProcess)
def run(cmd, mSec=None, stdin=None, stdout=None, stderr=None, **kw):
"""
Run cmd as a child process and return exit code.
mSec: terminate cmd after specified number of milliseconds
stdin, stdout, stderr:
file objects for child I/O (use hStdin etc. to attach
handles instead of files); default is caller's stdin,
stdout & stderr;
kw: see Process.__init__ for more keyword options
"""
if stdin is not None:
kw['hStdin'] = msvcrt.get_osfhandle(stdin.fileno())
if stdout is not None:
kw['hStdout'] = msvcrt.get_osfhandle(stdout.fileno())
if stderr is not None:
kw['hStderr'] = msvcrt.get_osfhandle(stderr.fileno())
child = Process(cmd, **kw)
if child.wait(mSec) != win32event.WAIT_OBJECT_0:
child.kill()
raise WindowsError, 'process timeout exceeded'
return child.exitCode()
if __name__ == '__main__':
# Pipe commands to a shell and display the output in notepad
print 'Testing winprocess.py...'
import tempfile
timeoutSeconds = 15
cmdString = """\
REM Test of winprocess.py piping commands to a shell.\r
REM This window will close in %d seconds.\r
vol\r
net user\r
_this_is_a_test_of_stderr_\r
""" % timeoutSeconds
cmd, out = tempfile.TemporaryFile(), tempfile.TemporaryFile()
cmd.write(cmdString)
cmd.seek(0)
print 'CMD.EXE exit code:', run('cmd.exe', show=0, stdin=cmd,
stdout=out, stderr=out)
cmd.close()
print 'NOTEPAD exit code:', run('notepad.exe %s' % out.file.name,
show=win32con.SW_MAXIMIZE,
mSec=timeoutSeconds*1000)
out.close()
<|fim▁end|> | """
EnumWindows callback - sends WM_CLOSE to any window
owned by this process.
"""
TId, PId = win32process.GetWindowThreadProcessId(hwnd)
if PId == self.PId:
win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0) |
<|file_name|>winprocess.py<|end_file_name|><|fim▁begin|>"""
Windows Process Control
winprocess.run launches a child process and returns the exit code.
Optionally, it can:
redirect stdin, stdout & stderr to files
run the command as another user
limit the process's running time
control the process window (location, size, window state, desktop)
Works on Windows NT, 2000 & XP. Requires Mark Hammond's win32
extensions.
This code is free for any purpose, with no warranty of any kind.
-- John B. Dell'Aquila <[email protected]>
"""
import win32api, win32process, win32security
import win32event, win32con, msvcrt, win32gui
def logonUser(loginString):
"""
Login as specified user and return handle.
loginString: 'Domain\nUser\nPassword'; for local
login use . or empty string as domain
e.g. '.\nadministrator\nsecret_password'
"""
domain, user, passwd = loginString.split('\n')
return win32security.LogonUser(
user,
domain,
passwd,
win32con.LOGON32_LOGON_INTERACTIVE,
win32con.LOGON32_PROVIDER_DEFAULT
)
class Process:
"""
A Windows process.
"""
def __init__(self, cmd, login=None,
hStdin=None, hStdout=None, hStderr=None,
show=1, xy=None, xySize=None,
desktop=None):
"""
Create a Windows process.
cmd: command to run
login: run as user 'Domain\nUser\nPassword'
hStdin, hStdout, hStderr:
handles for process I/O; default is caller's stdin,
stdout & stderr
show: wShowWindow (0=SW_HIDE, 1=SW_NORMAL, ...)
xy: window offset (x, y) of upper left corner in pixels
xySize: window size (width, height) in pixels
desktop: lpDesktop - name of desktop e.g. 'winsta0\\default'
None = inherit current desktop
'' = create new desktop if necessary
User calling login requires additional privileges:
Act as part of the operating system [not needed on Windows XP]
Increase quotas
Replace a process level token
Login string must EITHER be an administrator's account
(ordinary user can't access current desktop - see Microsoft
Q165194) OR use desktop='' to run another desktop invisibly
(may be very slow to startup & finalize).
"""
si = win32process.STARTUPINFO()
si.dwFlags = (win32con.STARTF_USESTDHANDLES ^
win32con.STARTF_USESHOWWINDOW)
if hStdin is None:
si.hStdInput = win32api.GetStdHandle(win32api.STD_INPUT_HANDLE)
else:
si.hStdInput = hStdin
if hStdout is None:
si.hStdOutput = win32api.GetStdHandle(win32api.STD_OUTPUT_HANDLE)
else:
si.hStdOutput = hStdout
if hStderr is None:
si.hStdError = win32api.GetStdHandle(win32api.STD_ERROR_HANDLE)
else:
si.hStdError = hStderr
si.wShowWindow = show
if xy is not None:
si.dwX, si.dwY = xy
si.dwFlags ^= win32con.STARTF_USEPOSITION
if xySize is not None:
si.dwXSize, si.dwYSize = xySize
si.dwFlags ^= win32con.STARTF_USESIZE
if desktop is not None:
si.lpDesktop = desktop
procArgs = (None, # appName
cmd, # commandLine
None, # processAttributes
None, # threadAttributes
1, # bInheritHandles
win32process.CREATE_NEW_CONSOLE, # dwCreationFlags
None, # newEnvironment
None, # currentDirectory
si) # startupinfo
if login is not None:
hUser = logonUser(login)
win32security.ImpersonateLoggedOnUser(hUser)
procHandles = win32process.CreateProcessAsUser(hUser, *procArgs)
win32security.RevertToSelf()
else:
procHandles = win32process.CreateProcess(*procArgs)
self.hProcess, self.hThread, self.PId, self.TId = procHandles
def wait(self, mSec=None):
"""
Wait for process to finish or for specified number of
milliseconds to elapse.
"""
if mSec is None:
mSec = win32event.INFINITE
return win32event.WaitForSingleObject(self.hProcess, mSec)
def kill(self, gracePeriod=5000):
"""
Kill process. Try for an orderly shutdown via WM_CLOSE. If
still running after gracePeriod (5 sec. default), terminate.
"""
win32gui.EnumWindows(self.__close__, 0)
if self.wait(gracePeriod) != win32event.WAIT_OBJECT_0:
win32process.TerminateProcess(self.hProcess, 0)
win32api.Sleep(100) # wait for resources to be released
def __close__(self, hwnd, dummy):
"""
EnumWindows callback - sends WM_CLOSE to any window
owned by this process.
"""
TId, PId = win32process.GetWindowThreadProcessId(hwnd)
if PId == self.PId:
win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0)
def exitCode(self):
<|fim_middle|>
def run(cmd, mSec=None, stdin=None, stdout=None, stderr=None, **kw):
"""
Run cmd as a child process and return exit code.
mSec: terminate cmd after specified number of milliseconds
stdin, stdout, stderr:
file objects for child I/O (use hStdin etc. to attach
handles instead of files); default is caller's stdin,
stdout & stderr;
kw: see Process.__init__ for more keyword options
"""
if stdin is not None:
kw['hStdin'] = msvcrt.get_osfhandle(stdin.fileno())
if stdout is not None:
kw['hStdout'] = msvcrt.get_osfhandle(stdout.fileno())
if stderr is not None:
kw['hStderr'] = msvcrt.get_osfhandle(stderr.fileno())
child = Process(cmd, **kw)
if child.wait(mSec) != win32event.WAIT_OBJECT_0:
child.kill()
raise WindowsError, 'process timeout exceeded'
return child.exitCode()
if __name__ == '__main__':
# Pipe commands to a shell and display the output in notepad
print 'Testing winprocess.py...'
import tempfile
timeoutSeconds = 15
cmdString = """\
REM Test of winprocess.py piping commands to a shell.\r
REM This window will close in %d seconds.\r
vol\r
net user\r
_this_is_a_test_of_stderr_\r
""" % timeoutSeconds
cmd, out = tempfile.TemporaryFile(), tempfile.TemporaryFile()
cmd.write(cmdString)
cmd.seek(0)
print 'CMD.EXE exit code:', run('cmd.exe', show=0, stdin=cmd,
stdout=out, stderr=out)
cmd.close()
print 'NOTEPAD exit code:', run('notepad.exe %s' % out.file.name,
show=win32con.SW_MAXIMIZE,
mSec=timeoutSeconds*1000)
out.close()
<|fim▁end|> | """
Return process exit code.
"""
return win32process.GetExitCodeProcess(self.hProcess) |
<|file_name|>winprocess.py<|end_file_name|><|fim▁begin|>"""
Windows Process Control
winprocess.run launches a child process and returns the exit code.
Optionally, it can:
redirect stdin, stdout & stderr to files
run the command as another user
limit the process's running time
control the process window (location, size, window state, desktop)
Works on Windows NT, 2000 & XP. Requires Mark Hammond's win32
extensions.
This code is free for any purpose, with no warranty of any kind.
-- John B. Dell'Aquila <[email protected]>
"""
import win32api, win32process, win32security
import win32event, win32con, msvcrt, win32gui
def logonUser(loginString):
"""
Login as specified user and return handle.
loginString: 'Domain\nUser\nPassword'; for local
login use . or empty string as domain
e.g. '.\nadministrator\nsecret_password'
"""
domain, user, passwd = loginString.split('\n')
return win32security.LogonUser(
user,
domain,
passwd,
win32con.LOGON32_LOGON_INTERACTIVE,
win32con.LOGON32_PROVIDER_DEFAULT
)
class Process:
"""
A Windows process.
"""
def __init__(self, cmd, login=None,
hStdin=None, hStdout=None, hStderr=None,
show=1, xy=None, xySize=None,
desktop=None):
"""
Create a Windows process.
cmd: command to run
login: run as user 'Domain\nUser\nPassword'
hStdin, hStdout, hStderr:
handles for process I/O; default is caller's stdin,
stdout & stderr
show: wShowWindow (0=SW_HIDE, 1=SW_NORMAL, ...)
xy: window offset (x, y) of upper left corner in pixels
xySize: window size (width, height) in pixels
desktop: lpDesktop - name of desktop e.g. 'winsta0\\default'
None = inherit current desktop
'' = create new desktop if necessary
User calling login requires additional privileges:
Act as part of the operating system [not needed on Windows XP]
Increase quotas
Replace a process level token
Login string must EITHER be an administrator's account
(ordinary user can't access current desktop - see Microsoft
Q165194) OR use desktop='' to run another desktop invisibly
(may be very slow to startup & finalize).
"""
si = win32process.STARTUPINFO()
si.dwFlags = (win32con.STARTF_USESTDHANDLES ^
win32con.STARTF_USESHOWWINDOW)
if hStdin is None:
si.hStdInput = win32api.GetStdHandle(win32api.STD_INPUT_HANDLE)
else:
si.hStdInput = hStdin
if hStdout is None:
si.hStdOutput = win32api.GetStdHandle(win32api.STD_OUTPUT_HANDLE)
else:
si.hStdOutput = hStdout
if hStderr is None:
si.hStdError = win32api.GetStdHandle(win32api.STD_ERROR_HANDLE)
else:
si.hStdError = hStderr
si.wShowWindow = show
if xy is not None:
si.dwX, si.dwY = xy
si.dwFlags ^= win32con.STARTF_USEPOSITION
if xySize is not None:
si.dwXSize, si.dwYSize = xySize
si.dwFlags ^= win32con.STARTF_USESIZE
if desktop is not None:
si.lpDesktop = desktop
procArgs = (None, # appName
cmd, # commandLine
None, # processAttributes
None, # threadAttributes
1, # bInheritHandles
win32process.CREATE_NEW_CONSOLE, # dwCreationFlags
None, # newEnvironment
None, # currentDirectory
si) # startupinfo
if login is not None:
hUser = logonUser(login)
win32security.ImpersonateLoggedOnUser(hUser)
procHandles = win32process.CreateProcessAsUser(hUser, *procArgs)
win32security.RevertToSelf()
else:
procHandles = win32process.CreateProcess(*procArgs)
self.hProcess, self.hThread, self.PId, self.TId = procHandles
def wait(self, mSec=None):
"""
Wait for process to finish or for specified number of
milliseconds to elapse.
"""
if mSec is None:
mSec = win32event.INFINITE
return win32event.WaitForSingleObject(self.hProcess, mSec)
def kill(self, gracePeriod=5000):
"""
Kill process. Try for an orderly shutdown via WM_CLOSE. If
still running after gracePeriod (5 sec. default), terminate.
"""
win32gui.EnumWindows(self.__close__, 0)
if self.wait(gracePeriod) != win32event.WAIT_OBJECT_0:
win32process.TerminateProcess(self.hProcess, 0)
win32api.Sleep(100) # wait for resources to be released
def __close__(self, hwnd, dummy):
"""
EnumWindows callback - sends WM_CLOSE to any window
owned by this process.
"""
TId, PId = win32process.GetWindowThreadProcessId(hwnd)
if PId == self.PId:
win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0)
def exitCode(self):
"""
Return process exit code.
"""
return win32process.GetExitCodeProcess(self.hProcess)
def run(cmd, mSec=None, stdin=None, stdout=None, stderr=None, **kw):
<|fim_middle|>
if __name__ == '__main__':
# Pipe commands to a shell and display the output in notepad
print 'Testing winprocess.py...'
import tempfile
timeoutSeconds = 15
cmdString = """\
REM Test of winprocess.py piping commands to a shell.\r
REM This window will close in %d seconds.\r
vol\r
net user\r
_this_is_a_test_of_stderr_\r
""" % timeoutSeconds
cmd, out = tempfile.TemporaryFile(), tempfile.TemporaryFile()
cmd.write(cmdString)
cmd.seek(0)
print 'CMD.EXE exit code:', run('cmd.exe', show=0, stdin=cmd,
stdout=out, stderr=out)
cmd.close()
print 'NOTEPAD exit code:', run('notepad.exe %s' % out.file.name,
show=win32con.SW_MAXIMIZE,
mSec=timeoutSeconds*1000)
out.close()
<|fim▁end|> | """
Run cmd as a child process and return exit code.
mSec: terminate cmd after specified number of milliseconds
stdin, stdout, stderr:
file objects for child I/O (use hStdin etc. to attach
handles instead of files); default is caller's stdin,
stdout & stderr;
kw: see Process.__init__ for more keyword options
"""
if stdin is not None:
kw['hStdin'] = msvcrt.get_osfhandle(stdin.fileno())
if stdout is not None:
kw['hStdout'] = msvcrt.get_osfhandle(stdout.fileno())
if stderr is not None:
kw['hStderr'] = msvcrt.get_osfhandle(stderr.fileno())
child = Process(cmd, **kw)
if child.wait(mSec) != win32event.WAIT_OBJECT_0:
child.kill()
raise WindowsError, 'process timeout exceeded'
return child.exitCode() |
<|file_name|>winprocess.py<|end_file_name|><|fim▁begin|>"""
Windows Process Control
winprocess.run launches a child process and returns the exit code.
Optionally, it can:
redirect stdin, stdout & stderr to files
run the command as another user
limit the process's running time
control the process window (location, size, window state, desktop)
Works on Windows NT, 2000 & XP. Requires Mark Hammond's win32
extensions.
This code is free for any purpose, with no warranty of any kind.
-- John B. Dell'Aquila <[email protected]>
"""
import win32api, win32process, win32security
import win32event, win32con, msvcrt, win32gui
def logonUser(loginString):
"""
Login as specified user and return handle.
loginString: 'Domain\nUser\nPassword'; for local
login use . or empty string as domain
e.g. '.\nadministrator\nsecret_password'
"""
domain, user, passwd = loginString.split('\n')
return win32security.LogonUser(
user,
domain,
passwd,
win32con.LOGON32_LOGON_INTERACTIVE,
win32con.LOGON32_PROVIDER_DEFAULT
)
class Process:
"""
A Windows process.
"""
def __init__(self, cmd, login=None,
hStdin=None, hStdout=None, hStderr=None,
show=1, xy=None, xySize=None,
desktop=None):
"""
Create a Windows process.
cmd: command to run
login: run as user 'Domain\nUser\nPassword'
hStdin, hStdout, hStderr:
handles for process I/O; default is caller's stdin,
stdout & stderr
show: wShowWindow (0=SW_HIDE, 1=SW_NORMAL, ...)
xy: window offset (x, y) of upper left corner in pixels
xySize: window size (width, height) in pixels
desktop: lpDesktop - name of desktop e.g. 'winsta0\\default'
None = inherit current desktop
'' = create new desktop if necessary
User calling login requires additional privileges:
Act as part of the operating system [not needed on Windows XP]
Increase quotas
Replace a process level token
Login string must EITHER be an administrator's account
(ordinary user can't access current desktop - see Microsoft
Q165194) OR use desktop='' to run another desktop invisibly
(may be very slow to startup & finalize).
"""
si = win32process.STARTUPINFO()
si.dwFlags = (win32con.STARTF_USESTDHANDLES ^
win32con.STARTF_USESHOWWINDOW)
if hStdin is None:
<|fim_middle|>
else:
si.hStdInput = hStdin
if hStdout is None:
si.hStdOutput = win32api.GetStdHandle(win32api.STD_OUTPUT_HANDLE)
else:
si.hStdOutput = hStdout
if hStderr is None:
si.hStdError = win32api.GetStdHandle(win32api.STD_ERROR_HANDLE)
else:
si.hStdError = hStderr
si.wShowWindow = show
if xy is not None:
si.dwX, si.dwY = xy
si.dwFlags ^= win32con.STARTF_USEPOSITION
if xySize is not None:
si.dwXSize, si.dwYSize = xySize
si.dwFlags ^= win32con.STARTF_USESIZE
if desktop is not None:
si.lpDesktop = desktop
procArgs = (None, # appName
cmd, # commandLine
None, # processAttributes
None, # threadAttributes
1, # bInheritHandles
win32process.CREATE_NEW_CONSOLE, # dwCreationFlags
None, # newEnvironment
None, # currentDirectory
si) # startupinfo
if login is not None:
hUser = logonUser(login)
win32security.ImpersonateLoggedOnUser(hUser)
procHandles = win32process.CreateProcessAsUser(hUser, *procArgs)
win32security.RevertToSelf()
else:
procHandles = win32process.CreateProcess(*procArgs)
self.hProcess, self.hThread, self.PId, self.TId = procHandles
def wait(self, mSec=None):
"""
Wait for process to finish or for specified number of
milliseconds to elapse.
"""
if mSec is None:
mSec = win32event.INFINITE
return win32event.WaitForSingleObject(self.hProcess, mSec)
def kill(self, gracePeriod=5000):
"""
Kill process. Try for an orderly shutdown via WM_CLOSE. If
still running after gracePeriod (5 sec. default), terminate.
"""
win32gui.EnumWindows(self.__close__, 0)
if self.wait(gracePeriod) != win32event.WAIT_OBJECT_0:
win32process.TerminateProcess(self.hProcess, 0)
win32api.Sleep(100) # wait for resources to be released
def __close__(self, hwnd, dummy):
"""
EnumWindows callback - sends WM_CLOSE to any window
owned by this process.
"""
TId, PId = win32process.GetWindowThreadProcessId(hwnd)
if PId == self.PId:
win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0)
def exitCode(self):
"""
Return process exit code.
"""
return win32process.GetExitCodeProcess(self.hProcess)
def run(cmd, mSec=None, stdin=None, stdout=None, stderr=None, **kw):
"""
Run cmd as a child process and return exit code.
mSec: terminate cmd after specified number of milliseconds
stdin, stdout, stderr:
file objects for child I/O (use hStdin etc. to attach
handles instead of files); default is caller's stdin,
stdout & stderr;
kw: see Process.__init__ for more keyword options
"""
if stdin is not None:
kw['hStdin'] = msvcrt.get_osfhandle(stdin.fileno())
if stdout is not None:
kw['hStdout'] = msvcrt.get_osfhandle(stdout.fileno())
if stderr is not None:
kw['hStderr'] = msvcrt.get_osfhandle(stderr.fileno())
child = Process(cmd, **kw)
if child.wait(mSec) != win32event.WAIT_OBJECT_0:
child.kill()
raise WindowsError, 'process timeout exceeded'
return child.exitCode()
if __name__ == '__main__':
# Pipe commands to a shell and display the output in notepad
print 'Testing winprocess.py...'
import tempfile
timeoutSeconds = 15
cmdString = """\
REM Test of winprocess.py piping commands to a shell.\r
REM This window will close in %d seconds.\r
vol\r
net user\r
_this_is_a_test_of_stderr_\r
""" % timeoutSeconds
cmd, out = tempfile.TemporaryFile(), tempfile.TemporaryFile()
cmd.write(cmdString)
cmd.seek(0)
print 'CMD.EXE exit code:', run('cmd.exe', show=0, stdin=cmd,
stdout=out, stderr=out)
cmd.close()
print 'NOTEPAD exit code:', run('notepad.exe %s' % out.file.name,
show=win32con.SW_MAXIMIZE,
mSec=timeoutSeconds*1000)
out.close()
<|fim▁end|> | si.hStdInput = win32api.GetStdHandle(win32api.STD_INPUT_HANDLE) |
<|file_name|>winprocess.py<|end_file_name|><|fim▁begin|>"""
Windows Process Control
winprocess.run launches a child process and returns the exit code.
Optionally, it can:
redirect stdin, stdout & stderr to files
run the command as another user
limit the process's running time
control the process window (location, size, window state, desktop)
Works on Windows NT, 2000 & XP. Requires Mark Hammond's win32
extensions.
This code is free for any purpose, with no warranty of any kind.
-- John B. Dell'Aquila <[email protected]>
"""
import win32api, win32process, win32security
import win32event, win32con, msvcrt, win32gui
def logonUser(loginString):
"""
Login as specified user and return handle.
loginString: 'Domain\nUser\nPassword'; for local
login use . or empty string as domain
e.g. '.\nadministrator\nsecret_password'
"""
domain, user, passwd = loginString.split('\n')
return win32security.LogonUser(
user,
domain,
passwd,
win32con.LOGON32_LOGON_INTERACTIVE,
win32con.LOGON32_PROVIDER_DEFAULT
)
class Process:
"""
A Windows process.
"""
def __init__(self, cmd, login=None,
hStdin=None, hStdout=None, hStderr=None,
show=1, xy=None, xySize=None,
desktop=None):
"""
Create a Windows process.
cmd: command to run
login: run as user 'Domain\nUser\nPassword'
hStdin, hStdout, hStderr:
handles for process I/O; default is caller's stdin,
stdout & stderr
show: wShowWindow (0=SW_HIDE, 1=SW_NORMAL, ...)
xy: window offset (x, y) of upper left corner in pixels
xySize: window size (width, height) in pixels
desktop: lpDesktop - name of desktop e.g. 'winsta0\\default'
None = inherit current desktop
'' = create new desktop if necessary
User calling login requires additional privileges:
Act as part of the operating system [not needed on Windows XP]
Increase quotas
Replace a process level token
Login string must EITHER be an administrator's account
(ordinary user can't access current desktop - see Microsoft
Q165194) OR use desktop='' to run another desktop invisibly
(may be very slow to startup & finalize).
"""
si = win32process.STARTUPINFO()
si.dwFlags = (win32con.STARTF_USESTDHANDLES ^
win32con.STARTF_USESHOWWINDOW)
if hStdin is None:
si.hStdInput = win32api.GetStdHandle(win32api.STD_INPUT_HANDLE)
else:
<|fim_middle|>
if hStdout is None:
si.hStdOutput = win32api.GetStdHandle(win32api.STD_OUTPUT_HANDLE)
else:
si.hStdOutput = hStdout
if hStderr is None:
si.hStdError = win32api.GetStdHandle(win32api.STD_ERROR_HANDLE)
else:
si.hStdError = hStderr
si.wShowWindow = show
if xy is not None:
si.dwX, si.dwY = xy
si.dwFlags ^= win32con.STARTF_USEPOSITION
if xySize is not None:
si.dwXSize, si.dwYSize = xySize
si.dwFlags ^= win32con.STARTF_USESIZE
if desktop is not None:
si.lpDesktop = desktop
procArgs = (None, # appName
cmd, # commandLine
None, # processAttributes
None, # threadAttributes
1, # bInheritHandles
win32process.CREATE_NEW_CONSOLE, # dwCreationFlags
None, # newEnvironment
None, # currentDirectory
si) # startupinfo
if login is not None:
hUser = logonUser(login)
win32security.ImpersonateLoggedOnUser(hUser)
procHandles = win32process.CreateProcessAsUser(hUser, *procArgs)
win32security.RevertToSelf()
else:
procHandles = win32process.CreateProcess(*procArgs)
self.hProcess, self.hThread, self.PId, self.TId = procHandles
def wait(self, mSec=None):
"""
Wait for process to finish or for specified number of
milliseconds to elapse.
"""
if mSec is None:
mSec = win32event.INFINITE
return win32event.WaitForSingleObject(self.hProcess, mSec)
def kill(self, gracePeriod=5000):
"""
Kill process. Try for an orderly shutdown via WM_CLOSE. If
still running after gracePeriod (5 sec. default), terminate.
"""
win32gui.EnumWindows(self.__close__, 0)
if self.wait(gracePeriod) != win32event.WAIT_OBJECT_0:
win32process.TerminateProcess(self.hProcess, 0)
win32api.Sleep(100) # wait for resources to be released
def __close__(self, hwnd, dummy):
"""
EnumWindows callback - sends WM_CLOSE to any window
owned by this process.
"""
TId, PId = win32process.GetWindowThreadProcessId(hwnd)
if PId == self.PId:
win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0)
def exitCode(self):
"""
Return process exit code.
"""
return win32process.GetExitCodeProcess(self.hProcess)
def run(cmd, mSec=None, stdin=None, stdout=None, stderr=None, **kw):
"""
Run cmd as a child process and return exit code.
mSec: terminate cmd after specified number of milliseconds
stdin, stdout, stderr:
file objects for child I/O (use hStdin etc. to attach
handles instead of files); default is caller's stdin,
stdout & stderr;
kw: see Process.__init__ for more keyword options
"""
if stdin is not None:
kw['hStdin'] = msvcrt.get_osfhandle(stdin.fileno())
if stdout is not None:
kw['hStdout'] = msvcrt.get_osfhandle(stdout.fileno())
if stderr is not None:
kw['hStderr'] = msvcrt.get_osfhandle(stderr.fileno())
child = Process(cmd, **kw)
if child.wait(mSec) != win32event.WAIT_OBJECT_0:
child.kill()
raise WindowsError, 'process timeout exceeded'
return child.exitCode()
if __name__ == '__main__':
# Pipe commands to a shell and display the output in notepad
print 'Testing winprocess.py...'
import tempfile
timeoutSeconds = 15
cmdString = """\
REM Test of winprocess.py piping commands to a shell.\r
REM This window will close in %d seconds.\r
vol\r
net user\r
_this_is_a_test_of_stderr_\r
""" % timeoutSeconds
cmd, out = tempfile.TemporaryFile(), tempfile.TemporaryFile()
cmd.write(cmdString)
cmd.seek(0)
print 'CMD.EXE exit code:', run('cmd.exe', show=0, stdin=cmd,
stdout=out, stderr=out)
cmd.close()
print 'NOTEPAD exit code:', run('notepad.exe %s' % out.file.name,
show=win32con.SW_MAXIMIZE,
mSec=timeoutSeconds*1000)
out.close()
<|fim▁end|> | si.hStdInput = hStdin |
<|file_name|>winprocess.py<|end_file_name|><|fim▁begin|>"""
Windows Process Control
winprocess.run launches a child process and returns the exit code.
Optionally, it can:
redirect stdin, stdout & stderr to files
run the command as another user
limit the process's running time
control the process window (location, size, window state, desktop)
Works on Windows NT, 2000 & XP. Requires Mark Hammond's win32
extensions.
This code is free for any purpose, with no warranty of any kind.
-- John B. Dell'Aquila <[email protected]>
"""
import win32api, win32process, win32security
import win32event, win32con, msvcrt, win32gui
def logonUser(loginString):
"""
Login as specified user and return handle.
loginString: 'Domain\nUser\nPassword'; for local
login use . or empty string as domain
e.g. '.\nadministrator\nsecret_password'
"""
domain, user, passwd = loginString.split('\n')
return win32security.LogonUser(
user,
domain,
passwd,
win32con.LOGON32_LOGON_INTERACTIVE,
win32con.LOGON32_PROVIDER_DEFAULT
)
class Process:
"""
A Windows process.
"""
def __init__(self, cmd, login=None,
hStdin=None, hStdout=None, hStderr=None,
show=1, xy=None, xySize=None,
desktop=None):
"""
Create a Windows process.
cmd: command to run
login: run as user 'Domain\nUser\nPassword'
hStdin, hStdout, hStderr:
handles for process I/O; default is caller's stdin,
stdout & stderr
show: wShowWindow (0=SW_HIDE, 1=SW_NORMAL, ...)
xy: window offset (x, y) of upper left corner in pixels
xySize: window size (width, height) in pixels
desktop: lpDesktop - name of desktop e.g. 'winsta0\\default'
None = inherit current desktop
'' = create new desktop if necessary
User calling login requires additional privileges:
Act as part of the operating system [not needed on Windows XP]
Increase quotas
Replace a process level token
Login string must EITHER be an administrator's account
(ordinary user can't access current desktop - see Microsoft
Q165194) OR use desktop='' to run another desktop invisibly
(may be very slow to startup & finalize).
"""
si = win32process.STARTUPINFO()
si.dwFlags = (win32con.STARTF_USESTDHANDLES ^
win32con.STARTF_USESHOWWINDOW)
if hStdin is None:
si.hStdInput = win32api.GetStdHandle(win32api.STD_INPUT_HANDLE)
else:
si.hStdInput = hStdin
if hStdout is None:
<|fim_middle|>
else:
si.hStdOutput = hStdout
if hStderr is None:
si.hStdError = win32api.GetStdHandle(win32api.STD_ERROR_HANDLE)
else:
si.hStdError = hStderr
si.wShowWindow = show
if xy is not None:
si.dwX, si.dwY = xy
si.dwFlags ^= win32con.STARTF_USEPOSITION
if xySize is not None:
si.dwXSize, si.dwYSize = xySize
si.dwFlags ^= win32con.STARTF_USESIZE
if desktop is not None:
si.lpDesktop = desktop
procArgs = (None, # appName
cmd, # commandLine
None, # processAttributes
None, # threadAttributes
1, # bInheritHandles
win32process.CREATE_NEW_CONSOLE, # dwCreationFlags
None, # newEnvironment
None, # currentDirectory
si) # startupinfo
if login is not None:
hUser = logonUser(login)
win32security.ImpersonateLoggedOnUser(hUser)
procHandles = win32process.CreateProcessAsUser(hUser, *procArgs)
win32security.RevertToSelf()
else:
procHandles = win32process.CreateProcess(*procArgs)
self.hProcess, self.hThread, self.PId, self.TId = procHandles
def wait(self, mSec=None):
"""
Wait for process to finish or for specified number of
milliseconds to elapse.
"""
if mSec is None:
mSec = win32event.INFINITE
return win32event.WaitForSingleObject(self.hProcess, mSec)
def kill(self, gracePeriod=5000):
"""
Kill process. Try for an orderly shutdown via WM_CLOSE. If
still running after gracePeriod (5 sec. default), terminate.
"""
win32gui.EnumWindows(self.__close__, 0)
if self.wait(gracePeriod) != win32event.WAIT_OBJECT_0:
win32process.TerminateProcess(self.hProcess, 0)
win32api.Sleep(100) # wait for resources to be released
def __close__(self, hwnd, dummy):
"""
EnumWindows callback - sends WM_CLOSE to any window
owned by this process.
"""
TId, PId = win32process.GetWindowThreadProcessId(hwnd)
if PId == self.PId:
win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0)
def exitCode(self):
"""
Return process exit code.
"""
return win32process.GetExitCodeProcess(self.hProcess)
def run(cmd, mSec=None, stdin=None, stdout=None, stderr=None, **kw):
"""
Run cmd as a child process and return exit code.
mSec: terminate cmd after specified number of milliseconds
stdin, stdout, stderr:
file objects for child I/O (use hStdin etc. to attach
handles instead of files); default is caller's stdin,
stdout & stderr;
kw: see Process.__init__ for more keyword options
"""
if stdin is not None:
kw['hStdin'] = msvcrt.get_osfhandle(stdin.fileno())
if stdout is not None:
kw['hStdout'] = msvcrt.get_osfhandle(stdout.fileno())
if stderr is not None:
kw['hStderr'] = msvcrt.get_osfhandle(stderr.fileno())
child = Process(cmd, **kw)
if child.wait(mSec) != win32event.WAIT_OBJECT_0:
child.kill()
raise WindowsError, 'process timeout exceeded'
return child.exitCode()
if __name__ == '__main__':
# Pipe commands to a shell and display the output in notepad
print 'Testing winprocess.py...'
import tempfile
timeoutSeconds = 15
cmdString = """\
REM Test of winprocess.py piping commands to a shell.\r
REM This window will close in %d seconds.\r
vol\r
net user\r
_this_is_a_test_of_stderr_\r
""" % timeoutSeconds
cmd, out = tempfile.TemporaryFile(), tempfile.TemporaryFile()
cmd.write(cmdString)
cmd.seek(0)
print 'CMD.EXE exit code:', run('cmd.exe', show=0, stdin=cmd,
stdout=out, stderr=out)
cmd.close()
print 'NOTEPAD exit code:', run('notepad.exe %s' % out.file.name,
show=win32con.SW_MAXIMIZE,
mSec=timeoutSeconds*1000)
out.close()
<|fim▁end|> | si.hStdOutput = win32api.GetStdHandle(win32api.STD_OUTPUT_HANDLE) |
<|file_name|>winprocess.py<|end_file_name|><|fim▁begin|>"""
Windows Process Control
winprocess.run launches a child process and returns the exit code.
Optionally, it can:
redirect stdin, stdout & stderr to files
run the command as another user
limit the process's running time
control the process window (location, size, window state, desktop)
Works on Windows NT, 2000 & XP. Requires Mark Hammond's win32
extensions.
This code is free for any purpose, with no warranty of any kind.
-- John B. Dell'Aquila <[email protected]>
"""
import win32api, win32process, win32security
import win32event, win32con, msvcrt, win32gui
def logonUser(loginString):
"""
Login as specified user and return handle.
loginString: 'Domain\nUser\nPassword'; for local
login use . or empty string as domain
e.g. '.\nadministrator\nsecret_password'
"""
domain, user, passwd = loginString.split('\n')
return win32security.LogonUser(
user,
domain,
passwd,
win32con.LOGON32_LOGON_INTERACTIVE,
win32con.LOGON32_PROVIDER_DEFAULT
)
class Process:
"""
A Windows process.
"""
def __init__(self, cmd, login=None,
hStdin=None, hStdout=None, hStderr=None,
show=1, xy=None, xySize=None,
desktop=None):
"""
Create a Windows process.
cmd: command to run
login: run as user 'Domain\nUser\nPassword'
hStdin, hStdout, hStderr:
handles for process I/O; default is caller's stdin,
stdout & stderr
show: wShowWindow (0=SW_HIDE, 1=SW_NORMAL, ...)
xy: window offset (x, y) of upper left corner in pixels
xySize: window size (width, height) in pixels
desktop: lpDesktop - name of desktop e.g. 'winsta0\\default'
None = inherit current desktop
'' = create new desktop if necessary
User calling login requires additional privileges:
Act as part of the operating system [not needed on Windows XP]
Increase quotas
Replace a process level token
Login string must EITHER be an administrator's account
(ordinary user can't access current desktop - see Microsoft
Q165194) OR use desktop='' to run another desktop invisibly
(may be very slow to startup & finalize).
"""
si = win32process.STARTUPINFO()
si.dwFlags = (win32con.STARTF_USESTDHANDLES ^
win32con.STARTF_USESHOWWINDOW)
if hStdin is None:
si.hStdInput = win32api.GetStdHandle(win32api.STD_INPUT_HANDLE)
else:
si.hStdInput = hStdin
if hStdout is None:
si.hStdOutput = win32api.GetStdHandle(win32api.STD_OUTPUT_HANDLE)
else:
<|fim_middle|>
if hStderr is None:
si.hStdError = win32api.GetStdHandle(win32api.STD_ERROR_HANDLE)
else:
si.hStdError = hStderr
si.wShowWindow = show
if xy is not None:
si.dwX, si.dwY = xy
si.dwFlags ^= win32con.STARTF_USEPOSITION
if xySize is not None:
si.dwXSize, si.dwYSize = xySize
si.dwFlags ^= win32con.STARTF_USESIZE
if desktop is not None:
si.lpDesktop = desktop
procArgs = (None, # appName
cmd, # commandLine
None, # processAttributes
None, # threadAttributes
1, # bInheritHandles
win32process.CREATE_NEW_CONSOLE, # dwCreationFlags
None, # newEnvironment
None, # currentDirectory
si) # startupinfo
if login is not None:
hUser = logonUser(login)
win32security.ImpersonateLoggedOnUser(hUser)
procHandles = win32process.CreateProcessAsUser(hUser, *procArgs)
win32security.RevertToSelf()
else:
procHandles = win32process.CreateProcess(*procArgs)
self.hProcess, self.hThread, self.PId, self.TId = procHandles
def wait(self, mSec=None):
"""
Wait for process to finish or for specified number of
milliseconds to elapse.
"""
if mSec is None:
mSec = win32event.INFINITE
return win32event.WaitForSingleObject(self.hProcess, mSec)
def kill(self, gracePeriod=5000):
"""
Kill process. Try for an orderly shutdown via WM_CLOSE. If
still running after gracePeriod (5 sec. default), terminate.
"""
win32gui.EnumWindows(self.__close__, 0)
if self.wait(gracePeriod) != win32event.WAIT_OBJECT_0:
win32process.TerminateProcess(self.hProcess, 0)
win32api.Sleep(100) # wait for resources to be released
def __close__(self, hwnd, dummy):
"""
EnumWindows callback - sends WM_CLOSE to any window
owned by this process.
"""
TId, PId = win32process.GetWindowThreadProcessId(hwnd)
if PId == self.PId:
win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0)
def exitCode(self):
"""
Return process exit code.
"""
return win32process.GetExitCodeProcess(self.hProcess)
def run(cmd, mSec=None, stdin=None, stdout=None, stderr=None, **kw):
"""
Run cmd as a child process and return exit code.
mSec: terminate cmd after specified number of milliseconds
stdin, stdout, stderr:
file objects for child I/O (use hStdin etc. to attach
handles instead of files); default is caller's stdin,
stdout & stderr;
kw: see Process.__init__ for more keyword options
"""
if stdin is not None:
kw['hStdin'] = msvcrt.get_osfhandle(stdin.fileno())
if stdout is not None:
kw['hStdout'] = msvcrt.get_osfhandle(stdout.fileno())
if stderr is not None:
kw['hStderr'] = msvcrt.get_osfhandle(stderr.fileno())
child = Process(cmd, **kw)
if child.wait(mSec) != win32event.WAIT_OBJECT_0:
child.kill()
raise WindowsError, 'process timeout exceeded'
return child.exitCode()
if __name__ == '__main__':
# Pipe commands to a shell and display the output in notepad
print 'Testing winprocess.py...'
import tempfile
timeoutSeconds = 15
cmdString = """\
REM Test of winprocess.py piping commands to a shell.\r
REM This window will close in %d seconds.\r
vol\r
net user\r
_this_is_a_test_of_stderr_\r
""" % timeoutSeconds
cmd, out = tempfile.TemporaryFile(), tempfile.TemporaryFile()
cmd.write(cmdString)
cmd.seek(0)
print 'CMD.EXE exit code:', run('cmd.exe', show=0, stdin=cmd,
stdout=out, stderr=out)
cmd.close()
print 'NOTEPAD exit code:', run('notepad.exe %s' % out.file.name,
show=win32con.SW_MAXIMIZE,
mSec=timeoutSeconds*1000)
out.close()
<|fim▁end|> | si.hStdOutput = hStdout |
<|file_name|>winprocess.py<|end_file_name|><|fim▁begin|>"""
Windows Process Control
winprocess.run launches a child process and returns the exit code.
Optionally, it can:
redirect stdin, stdout & stderr to files
run the command as another user
limit the process's running time
control the process window (location, size, window state, desktop)
Works on Windows NT, 2000 & XP. Requires Mark Hammond's win32
extensions.
This code is free for any purpose, with no warranty of any kind.
-- John B. Dell'Aquila <[email protected]>
"""
import win32api, win32process, win32security
import win32event, win32con, msvcrt, win32gui
def logonUser(loginString):
"""
Login as specified user and return handle.
loginString: 'Domain\nUser\nPassword'; for local
login use . or empty string as domain
e.g. '.\nadministrator\nsecret_password'
"""
domain, user, passwd = loginString.split('\n')
return win32security.LogonUser(
user,
domain,
passwd,
win32con.LOGON32_LOGON_INTERACTIVE,
win32con.LOGON32_PROVIDER_DEFAULT
)
class Process:
"""
A Windows process.
"""
def __init__(self, cmd, login=None,
hStdin=None, hStdout=None, hStderr=None,
show=1, xy=None, xySize=None,
desktop=None):
"""
Create a Windows process.
cmd: command to run
login: run as user 'Domain\nUser\nPassword'
hStdin, hStdout, hStderr:
handles for process I/O; default is caller's stdin,
stdout & stderr
show: wShowWindow (0=SW_HIDE, 1=SW_NORMAL, ...)
xy: window offset (x, y) of upper left corner in pixels
xySize: window size (width, height) in pixels
desktop: lpDesktop - name of desktop e.g. 'winsta0\\default'
None = inherit current desktop
'' = create new desktop if necessary
User calling login requires additional privileges:
Act as part of the operating system [not needed on Windows XP]
Increase quotas
Replace a process level token
Login string must EITHER be an administrator's account
(ordinary user can't access current desktop - see Microsoft
Q165194) OR use desktop='' to run another desktop invisibly
(may be very slow to startup & finalize).
"""
si = win32process.STARTUPINFO()
si.dwFlags = (win32con.STARTF_USESTDHANDLES ^
win32con.STARTF_USESHOWWINDOW)
if hStdin is None:
si.hStdInput = win32api.GetStdHandle(win32api.STD_INPUT_HANDLE)
else:
si.hStdInput = hStdin
if hStdout is None:
si.hStdOutput = win32api.GetStdHandle(win32api.STD_OUTPUT_HANDLE)
else:
si.hStdOutput = hStdout
if hStderr is None:
<|fim_middle|>
else:
si.hStdError = hStderr
si.wShowWindow = show
if xy is not None:
si.dwX, si.dwY = xy
si.dwFlags ^= win32con.STARTF_USEPOSITION
if xySize is not None:
si.dwXSize, si.dwYSize = xySize
si.dwFlags ^= win32con.STARTF_USESIZE
if desktop is not None:
si.lpDesktop = desktop
procArgs = (None, # appName
cmd, # commandLine
None, # processAttributes
None, # threadAttributes
1, # bInheritHandles
win32process.CREATE_NEW_CONSOLE, # dwCreationFlags
None, # newEnvironment
None, # currentDirectory
si) # startupinfo
if login is not None:
hUser = logonUser(login)
win32security.ImpersonateLoggedOnUser(hUser)
procHandles = win32process.CreateProcessAsUser(hUser, *procArgs)
win32security.RevertToSelf()
else:
procHandles = win32process.CreateProcess(*procArgs)
self.hProcess, self.hThread, self.PId, self.TId = procHandles
def wait(self, mSec=None):
"""
Wait for process to finish or for specified number of
milliseconds to elapse.
"""
if mSec is None:
mSec = win32event.INFINITE
return win32event.WaitForSingleObject(self.hProcess, mSec)
def kill(self, gracePeriod=5000):
"""
Kill process. Try for an orderly shutdown via WM_CLOSE. If
still running after gracePeriod (5 sec. default), terminate.
"""
win32gui.EnumWindows(self.__close__, 0)
if self.wait(gracePeriod) != win32event.WAIT_OBJECT_0:
win32process.TerminateProcess(self.hProcess, 0)
win32api.Sleep(100) # wait for resources to be released
def __close__(self, hwnd, dummy):
"""
EnumWindows callback - sends WM_CLOSE to any window
owned by this process.
"""
TId, PId = win32process.GetWindowThreadProcessId(hwnd)
if PId == self.PId:
win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0)
def exitCode(self):
"""
Return process exit code.
"""
return win32process.GetExitCodeProcess(self.hProcess)
def run(cmd, mSec=None, stdin=None, stdout=None, stderr=None, **kw):
"""
Run cmd as a child process and return exit code.
mSec: terminate cmd after specified number of milliseconds
stdin, stdout, stderr:
file objects for child I/O (use hStdin etc. to attach
handles instead of files); default is caller's stdin,
stdout & stderr;
kw: see Process.__init__ for more keyword options
"""
if stdin is not None:
kw['hStdin'] = msvcrt.get_osfhandle(stdin.fileno())
if stdout is not None:
kw['hStdout'] = msvcrt.get_osfhandle(stdout.fileno())
if stderr is not None:
kw['hStderr'] = msvcrt.get_osfhandle(stderr.fileno())
child = Process(cmd, **kw)
if child.wait(mSec) != win32event.WAIT_OBJECT_0:
child.kill()
raise WindowsError, 'process timeout exceeded'
return child.exitCode()
if __name__ == '__main__':
# Pipe commands to a shell and display the output in notepad
print 'Testing winprocess.py...'
import tempfile
timeoutSeconds = 15
cmdString = """\
REM Test of winprocess.py piping commands to a shell.\r
REM This window will close in %d seconds.\r
vol\r
net user\r
_this_is_a_test_of_stderr_\r
""" % timeoutSeconds
cmd, out = tempfile.TemporaryFile(), tempfile.TemporaryFile()
cmd.write(cmdString)
cmd.seek(0)
print 'CMD.EXE exit code:', run('cmd.exe', show=0, stdin=cmd,
stdout=out, stderr=out)
cmd.close()
print 'NOTEPAD exit code:', run('notepad.exe %s' % out.file.name,
show=win32con.SW_MAXIMIZE,
mSec=timeoutSeconds*1000)
out.close()
<|fim▁end|> | si.hStdError = win32api.GetStdHandle(win32api.STD_ERROR_HANDLE) |
<|file_name|>winprocess.py<|end_file_name|><|fim▁begin|>"""
Windows Process Control
winprocess.run launches a child process and returns the exit code.
Optionally, it can:
redirect stdin, stdout & stderr to files
run the command as another user
limit the process's running time
control the process window (location, size, window state, desktop)
Works on Windows NT, 2000 & XP. Requires Mark Hammond's win32
extensions.
This code is free for any purpose, with no warranty of any kind.
-- John B. Dell'Aquila <[email protected]>
"""
import win32api, win32process, win32security
import win32event, win32con, msvcrt, win32gui
def logonUser(loginString):
"""
Login as specified user and return handle.
loginString: 'Domain\nUser\nPassword'; for local
login use . or empty string as domain
e.g. '.\nadministrator\nsecret_password'
"""
domain, user, passwd = loginString.split('\n')
return win32security.LogonUser(
user,
domain,
passwd,
win32con.LOGON32_LOGON_INTERACTIVE,
win32con.LOGON32_PROVIDER_DEFAULT
)
class Process:
"""
A Windows process.
"""
def __init__(self, cmd, login=None,
hStdin=None, hStdout=None, hStderr=None,
show=1, xy=None, xySize=None,
desktop=None):
"""
Create a Windows process.
cmd: command to run
login: run as user 'Domain\nUser\nPassword'
hStdin, hStdout, hStderr:
handles for process I/O; default is caller's stdin,
stdout & stderr
show: wShowWindow (0=SW_HIDE, 1=SW_NORMAL, ...)
xy: window offset (x, y) of upper left corner in pixels
xySize: window size (width, height) in pixels
desktop: lpDesktop - name of desktop e.g. 'winsta0\\default'
None = inherit current desktop
'' = create new desktop if necessary
User calling login requires additional privileges:
Act as part of the operating system [not needed on Windows XP]
Increase quotas
Replace a process level token
Login string must EITHER be an administrator's account
(ordinary user can't access current desktop - see Microsoft
Q165194) OR use desktop='' to run another desktop invisibly
(may be very slow to startup & finalize).
"""
si = win32process.STARTUPINFO()
si.dwFlags = (win32con.STARTF_USESTDHANDLES ^
win32con.STARTF_USESHOWWINDOW)
if hStdin is None:
si.hStdInput = win32api.GetStdHandle(win32api.STD_INPUT_HANDLE)
else:
si.hStdInput = hStdin
if hStdout is None:
si.hStdOutput = win32api.GetStdHandle(win32api.STD_OUTPUT_HANDLE)
else:
si.hStdOutput = hStdout
if hStderr is None:
si.hStdError = win32api.GetStdHandle(win32api.STD_ERROR_HANDLE)
else:
<|fim_middle|>
si.wShowWindow = show
if xy is not None:
si.dwX, si.dwY = xy
si.dwFlags ^= win32con.STARTF_USEPOSITION
if xySize is not None:
si.dwXSize, si.dwYSize = xySize
si.dwFlags ^= win32con.STARTF_USESIZE
if desktop is not None:
si.lpDesktop = desktop
procArgs = (None, # appName
cmd, # commandLine
None, # processAttributes
None, # threadAttributes
1, # bInheritHandles
win32process.CREATE_NEW_CONSOLE, # dwCreationFlags
None, # newEnvironment
None, # currentDirectory
si) # startupinfo
if login is not None:
hUser = logonUser(login)
win32security.ImpersonateLoggedOnUser(hUser)
procHandles = win32process.CreateProcessAsUser(hUser, *procArgs)
win32security.RevertToSelf()
else:
procHandles = win32process.CreateProcess(*procArgs)
self.hProcess, self.hThread, self.PId, self.TId = procHandles
def wait(self, mSec=None):
"""
Wait for process to finish or for specified number of
milliseconds to elapse.
"""
if mSec is None:
mSec = win32event.INFINITE
return win32event.WaitForSingleObject(self.hProcess, mSec)
def kill(self, gracePeriod=5000):
"""
Kill process. Try for an orderly shutdown via WM_CLOSE. If
still running after gracePeriod (5 sec. default), terminate.
"""
win32gui.EnumWindows(self.__close__, 0)
if self.wait(gracePeriod) != win32event.WAIT_OBJECT_0:
win32process.TerminateProcess(self.hProcess, 0)
win32api.Sleep(100) # wait for resources to be released
def __close__(self, hwnd, dummy):
"""
EnumWindows callback - sends WM_CLOSE to any window
owned by this process.
"""
TId, PId = win32process.GetWindowThreadProcessId(hwnd)
if PId == self.PId:
win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0)
def exitCode(self):
"""
Return process exit code.
"""
return win32process.GetExitCodeProcess(self.hProcess)
def run(cmd, mSec=None, stdin=None, stdout=None, stderr=None, **kw):
"""
Run cmd as a child process and return exit code.
mSec: terminate cmd after specified number of milliseconds
stdin, stdout, stderr:
file objects for child I/O (use hStdin etc. to attach
handles instead of files); default is caller's stdin,
stdout & stderr;
kw: see Process.__init__ for more keyword options
"""
if stdin is not None:
kw['hStdin'] = msvcrt.get_osfhandle(stdin.fileno())
if stdout is not None:
kw['hStdout'] = msvcrt.get_osfhandle(stdout.fileno())
if stderr is not None:
kw['hStderr'] = msvcrt.get_osfhandle(stderr.fileno())
child = Process(cmd, **kw)
if child.wait(mSec) != win32event.WAIT_OBJECT_0:
child.kill()
raise WindowsError, 'process timeout exceeded'
return child.exitCode()
if __name__ == '__main__':
# Pipe commands to a shell and display the output in notepad
print 'Testing winprocess.py...'
import tempfile
timeoutSeconds = 15
cmdString = """\
REM Test of winprocess.py piping commands to a shell.\r
REM This window will close in %d seconds.\r
vol\r
net user\r
_this_is_a_test_of_stderr_\r
""" % timeoutSeconds
cmd, out = tempfile.TemporaryFile(), tempfile.TemporaryFile()
cmd.write(cmdString)
cmd.seek(0)
print 'CMD.EXE exit code:', run('cmd.exe', show=0, stdin=cmd,
stdout=out, stderr=out)
cmd.close()
print 'NOTEPAD exit code:', run('notepad.exe %s' % out.file.name,
show=win32con.SW_MAXIMIZE,
mSec=timeoutSeconds*1000)
out.close()
<|fim▁end|> | si.hStdError = hStderr |
<|file_name|>winprocess.py<|end_file_name|><|fim▁begin|>"""
Windows Process Control
winprocess.run launches a child process and returns the exit code.
Optionally, it can:
redirect stdin, stdout & stderr to files
run the command as another user
limit the process's running time
control the process window (location, size, window state, desktop)
Works on Windows NT, 2000 & XP. Requires Mark Hammond's win32
extensions.
This code is free for any purpose, with no warranty of any kind.
-- John B. Dell'Aquila <[email protected]>
"""
import win32api, win32process, win32security
import win32event, win32con, msvcrt, win32gui
def logonUser(loginString):
"""
Login as specified user and return handle.
loginString: 'Domain\nUser\nPassword'; for local
login use . or empty string as domain
e.g. '.\nadministrator\nsecret_password'
"""
domain, user, passwd = loginString.split('\n')
return win32security.LogonUser(
user,
domain,
passwd,
win32con.LOGON32_LOGON_INTERACTIVE,
win32con.LOGON32_PROVIDER_DEFAULT
)
class Process:
"""
A Windows process.
"""
def __init__(self, cmd, login=None,
hStdin=None, hStdout=None, hStderr=None,
show=1, xy=None, xySize=None,
desktop=None):
"""
Create a Windows process.
cmd: command to run
login: run as user 'Domain\nUser\nPassword'
hStdin, hStdout, hStderr:
handles for process I/O; default is caller's stdin,
stdout & stderr
show: wShowWindow (0=SW_HIDE, 1=SW_NORMAL, ...)
xy: window offset (x, y) of upper left corner in pixels
xySize: window size (width, height) in pixels
desktop: lpDesktop - name of desktop e.g. 'winsta0\\default'
None = inherit current desktop
'' = create new desktop if necessary
User calling login requires additional privileges:
Act as part of the operating system [not needed on Windows XP]
Increase quotas
Replace a process level token
Login string must EITHER be an administrator's account
(ordinary user can't access current desktop - see Microsoft
Q165194) OR use desktop='' to run another desktop invisibly
(may be very slow to startup & finalize).
"""
si = win32process.STARTUPINFO()
si.dwFlags = (win32con.STARTF_USESTDHANDLES ^
win32con.STARTF_USESHOWWINDOW)
if hStdin is None:
si.hStdInput = win32api.GetStdHandle(win32api.STD_INPUT_HANDLE)
else:
si.hStdInput = hStdin
if hStdout is None:
si.hStdOutput = win32api.GetStdHandle(win32api.STD_OUTPUT_HANDLE)
else:
si.hStdOutput = hStdout
if hStderr is None:
si.hStdError = win32api.GetStdHandle(win32api.STD_ERROR_HANDLE)
else:
si.hStdError = hStderr
si.wShowWindow = show
if xy is not None:
<|fim_middle|>
if xySize is not None:
si.dwXSize, si.dwYSize = xySize
si.dwFlags ^= win32con.STARTF_USESIZE
if desktop is not None:
si.lpDesktop = desktop
procArgs = (None, # appName
cmd, # commandLine
None, # processAttributes
None, # threadAttributes
1, # bInheritHandles
win32process.CREATE_NEW_CONSOLE, # dwCreationFlags
None, # newEnvironment
None, # currentDirectory
si) # startupinfo
if login is not None:
hUser = logonUser(login)
win32security.ImpersonateLoggedOnUser(hUser)
procHandles = win32process.CreateProcessAsUser(hUser, *procArgs)
win32security.RevertToSelf()
else:
procHandles = win32process.CreateProcess(*procArgs)
self.hProcess, self.hThread, self.PId, self.TId = procHandles
def wait(self, mSec=None):
"""
Wait for process to finish or for specified number of
milliseconds to elapse.
"""
if mSec is None:
mSec = win32event.INFINITE
return win32event.WaitForSingleObject(self.hProcess, mSec)
def kill(self, gracePeriod=5000):
"""
Kill process. Try for an orderly shutdown via WM_CLOSE. If
still running after gracePeriod (5 sec. default), terminate.
"""
win32gui.EnumWindows(self.__close__, 0)
if self.wait(gracePeriod) != win32event.WAIT_OBJECT_0:
win32process.TerminateProcess(self.hProcess, 0)
win32api.Sleep(100) # wait for resources to be released
def __close__(self, hwnd, dummy):
"""
EnumWindows callback - sends WM_CLOSE to any window
owned by this process.
"""
TId, PId = win32process.GetWindowThreadProcessId(hwnd)
if PId == self.PId:
win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0)
def exitCode(self):
"""
Return process exit code.
"""
return win32process.GetExitCodeProcess(self.hProcess)
def run(cmd, mSec=None, stdin=None, stdout=None, stderr=None, **kw):
"""
Run cmd as a child process and return exit code.
mSec: terminate cmd after specified number of milliseconds
stdin, stdout, stderr:
file objects for child I/O (use hStdin etc. to attach
handles instead of files); default is caller's stdin,
stdout & stderr;
kw: see Process.__init__ for more keyword options
"""
if stdin is not None:
kw['hStdin'] = msvcrt.get_osfhandle(stdin.fileno())
if stdout is not None:
kw['hStdout'] = msvcrt.get_osfhandle(stdout.fileno())
if stderr is not None:
kw['hStderr'] = msvcrt.get_osfhandle(stderr.fileno())
child = Process(cmd, **kw)
if child.wait(mSec) != win32event.WAIT_OBJECT_0:
child.kill()
raise WindowsError, 'process timeout exceeded'
return child.exitCode()
if __name__ == '__main__':
# Pipe commands to a shell and display the output in notepad
print 'Testing winprocess.py...'
import tempfile
timeoutSeconds = 15
cmdString = """\
REM Test of winprocess.py piping commands to a shell.\r
REM This window will close in %d seconds.\r
vol\r
net user\r
_this_is_a_test_of_stderr_\r
""" % timeoutSeconds
cmd, out = tempfile.TemporaryFile(), tempfile.TemporaryFile()
cmd.write(cmdString)
cmd.seek(0)
print 'CMD.EXE exit code:', run('cmd.exe', show=0, stdin=cmd,
stdout=out, stderr=out)
cmd.close()
print 'NOTEPAD exit code:', run('notepad.exe %s' % out.file.name,
show=win32con.SW_MAXIMIZE,
mSec=timeoutSeconds*1000)
out.close()
<|fim▁end|> | si.dwX, si.dwY = xy
si.dwFlags ^= win32con.STARTF_USEPOSITION |
<|file_name|>winprocess.py<|end_file_name|><|fim▁begin|>"""
Windows Process Control
winprocess.run launches a child process and returns the exit code.
Optionally, it can:
redirect stdin, stdout & stderr to files
run the command as another user
limit the process's running time
control the process window (location, size, window state, desktop)
Works on Windows NT, 2000 & XP. Requires Mark Hammond's win32
extensions.
This code is free for any purpose, with no warranty of any kind.
-- John B. Dell'Aquila <[email protected]>
"""
import win32api, win32process, win32security
import win32event, win32con, msvcrt, win32gui
def logonUser(loginString):
"""
Login as specified user and return handle.
loginString: 'Domain\nUser\nPassword'; for local
login use . or empty string as domain
e.g. '.\nadministrator\nsecret_password'
"""
domain, user, passwd = loginString.split('\n')
return win32security.LogonUser(
user,
domain,
passwd,
win32con.LOGON32_LOGON_INTERACTIVE,
win32con.LOGON32_PROVIDER_DEFAULT
)
class Process:
"""
A Windows process.
"""
def __init__(self, cmd, login=None,
hStdin=None, hStdout=None, hStderr=None,
show=1, xy=None, xySize=None,
desktop=None):
"""
Create a Windows process.
cmd: command to run
login: run as user 'Domain\nUser\nPassword'
hStdin, hStdout, hStderr:
handles for process I/O; default is caller's stdin,
stdout & stderr
show: wShowWindow (0=SW_HIDE, 1=SW_NORMAL, ...)
xy: window offset (x, y) of upper left corner in pixels
xySize: window size (width, height) in pixels
desktop: lpDesktop - name of desktop e.g. 'winsta0\\default'
None = inherit current desktop
'' = create new desktop if necessary
User calling login requires additional privileges:
Act as part of the operating system [not needed on Windows XP]
Increase quotas
Replace a process level token
Login string must EITHER be an administrator's account
(ordinary user can't access current desktop - see Microsoft
Q165194) OR use desktop='' to run another desktop invisibly
(may be very slow to startup & finalize).
"""
si = win32process.STARTUPINFO()
si.dwFlags = (win32con.STARTF_USESTDHANDLES ^
win32con.STARTF_USESHOWWINDOW)
if hStdin is None:
si.hStdInput = win32api.GetStdHandle(win32api.STD_INPUT_HANDLE)
else:
si.hStdInput = hStdin
if hStdout is None:
si.hStdOutput = win32api.GetStdHandle(win32api.STD_OUTPUT_HANDLE)
else:
si.hStdOutput = hStdout
if hStderr is None:
si.hStdError = win32api.GetStdHandle(win32api.STD_ERROR_HANDLE)
else:
si.hStdError = hStderr
si.wShowWindow = show
if xy is not None:
si.dwX, si.dwY = xy
si.dwFlags ^= win32con.STARTF_USEPOSITION
if xySize is not None:
<|fim_middle|>
if desktop is not None:
si.lpDesktop = desktop
procArgs = (None, # appName
cmd, # commandLine
None, # processAttributes
None, # threadAttributes
1, # bInheritHandles
win32process.CREATE_NEW_CONSOLE, # dwCreationFlags
None, # newEnvironment
None, # currentDirectory
si) # startupinfo
if login is not None:
hUser = logonUser(login)
win32security.ImpersonateLoggedOnUser(hUser)
procHandles = win32process.CreateProcessAsUser(hUser, *procArgs)
win32security.RevertToSelf()
else:
procHandles = win32process.CreateProcess(*procArgs)
self.hProcess, self.hThread, self.PId, self.TId = procHandles
def wait(self, mSec=None):
"""
Wait for process to finish or for specified number of
milliseconds to elapse.
"""
if mSec is None:
mSec = win32event.INFINITE
return win32event.WaitForSingleObject(self.hProcess, mSec)
def kill(self, gracePeriod=5000):
"""
Kill process. Try for an orderly shutdown via WM_CLOSE. If
still running after gracePeriod (5 sec. default), terminate.
"""
win32gui.EnumWindows(self.__close__, 0)
if self.wait(gracePeriod) != win32event.WAIT_OBJECT_0:
win32process.TerminateProcess(self.hProcess, 0)
win32api.Sleep(100) # wait for resources to be released
def __close__(self, hwnd, dummy):
"""
EnumWindows callback - sends WM_CLOSE to any window
owned by this process.
"""
TId, PId = win32process.GetWindowThreadProcessId(hwnd)
if PId == self.PId:
win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0)
def exitCode(self):
"""
Return process exit code.
"""
return win32process.GetExitCodeProcess(self.hProcess)
def run(cmd, mSec=None, stdin=None, stdout=None, stderr=None, **kw):
"""
Run cmd as a child process and return exit code.
mSec: terminate cmd after specified number of milliseconds
stdin, stdout, stderr:
file objects for child I/O (use hStdin etc. to attach
handles instead of files); default is caller's stdin,
stdout & stderr;
kw: see Process.__init__ for more keyword options
"""
if stdin is not None:
kw['hStdin'] = msvcrt.get_osfhandle(stdin.fileno())
if stdout is not None:
kw['hStdout'] = msvcrt.get_osfhandle(stdout.fileno())
if stderr is not None:
kw['hStderr'] = msvcrt.get_osfhandle(stderr.fileno())
child = Process(cmd, **kw)
if child.wait(mSec) != win32event.WAIT_OBJECT_0:
child.kill()
raise WindowsError, 'process timeout exceeded'
return child.exitCode()
if __name__ == '__main__':
# Pipe commands to a shell and display the output in notepad
print 'Testing winprocess.py...'
import tempfile
timeoutSeconds = 15
cmdString = """\
REM Test of winprocess.py piping commands to a shell.\r
REM This window will close in %d seconds.\r
vol\r
net user\r
_this_is_a_test_of_stderr_\r
""" % timeoutSeconds
cmd, out = tempfile.TemporaryFile(), tempfile.TemporaryFile()
cmd.write(cmdString)
cmd.seek(0)
print 'CMD.EXE exit code:', run('cmd.exe', show=0, stdin=cmd,
stdout=out, stderr=out)
cmd.close()
print 'NOTEPAD exit code:', run('notepad.exe %s' % out.file.name,
show=win32con.SW_MAXIMIZE,
mSec=timeoutSeconds*1000)
out.close()
<|fim▁end|> | si.dwXSize, si.dwYSize = xySize
si.dwFlags ^= win32con.STARTF_USESIZE |
<|file_name|>winprocess.py<|end_file_name|><|fim▁begin|>"""
Windows Process Control
winprocess.run launches a child process and returns the exit code.
Optionally, it can:
redirect stdin, stdout & stderr to files
run the command as another user
limit the process's running time
control the process window (location, size, window state, desktop)
Works on Windows NT, 2000 & XP. Requires Mark Hammond's win32
extensions.
This code is free for any purpose, with no warranty of any kind.
-- John B. Dell'Aquila <[email protected]>
"""
import win32api, win32process, win32security
import win32event, win32con, msvcrt, win32gui
def logonUser(loginString):
"""
Login as specified user and return handle.
loginString: 'Domain\nUser\nPassword'; for local
login use . or empty string as domain
e.g. '.\nadministrator\nsecret_password'
"""
domain, user, passwd = loginString.split('\n')
return win32security.LogonUser(
user,
domain,
passwd,
win32con.LOGON32_LOGON_INTERACTIVE,
win32con.LOGON32_PROVIDER_DEFAULT
)
class Process:
"""
A Windows process.
"""
def __init__(self, cmd, login=None,
hStdin=None, hStdout=None, hStderr=None,
show=1, xy=None, xySize=None,
desktop=None):
"""
Create a Windows process.
cmd: command to run
login: run as user 'Domain\nUser\nPassword'
hStdin, hStdout, hStderr:
handles for process I/O; default is caller's stdin,
stdout & stderr
show: wShowWindow (0=SW_HIDE, 1=SW_NORMAL, ...)
xy: window offset (x, y) of upper left corner in pixels
xySize: window size (width, height) in pixels
desktop: lpDesktop - name of desktop e.g. 'winsta0\\default'
None = inherit current desktop
'' = create new desktop if necessary
User calling login requires additional privileges:
Act as part of the operating system [not needed on Windows XP]
Increase quotas
Replace a process level token
Login string must EITHER be an administrator's account
(ordinary user can't access current desktop - see Microsoft
Q165194) OR use desktop='' to run another desktop invisibly
(may be very slow to startup & finalize).
"""
si = win32process.STARTUPINFO()
si.dwFlags = (win32con.STARTF_USESTDHANDLES ^
win32con.STARTF_USESHOWWINDOW)
if hStdin is None:
si.hStdInput = win32api.GetStdHandle(win32api.STD_INPUT_HANDLE)
else:
si.hStdInput = hStdin
if hStdout is None:
si.hStdOutput = win32api.GetStdHandle(win32api.STD_OUTPUT_HANDLE)
else:
si.hStdOutput = hStdout
if hStderr is None:
si.hStdError = win32api.GetStdHandle(win32api.STD_ERROR_HANDLE)
else:
si.hStdError = hStderr
si.wShowWindow = show
if xy is not None:
si.dwX, si.dwY = xy
si.dwFlags ^= win32con.STARTF_USEPOSITION
if xySize is not None:
si.dwXSize, si.dwYSize = xySize
si.dwFlags ^= win32con.STARTF_USESIZE
if desktop is not None:
<|fim_middle|>
procArgs = (None, # appName
cmd, # commandLine
None, # processAttributes
None, # threadAttributes
1, # bInheritHandles
win32process.CREATE_NEW_CONSOLE, # dwCreationFlags
None, # newEnvironment
None, # currentDirectory
si) # startupinfo
if login is not None:
hUser = logonUser(login)
win32security.ImpersonateLoggedOnUser(hUser)
procHandles = win32process.CreateProcessAsUser(hUser, *procArgs)
win32security.RevertToSelf()
else:
procHandles = win32process.CreateProcess(*procArgs)
self.hProcess, self.hThread, self.PId, self.TId = procHandles
def wait(self, mSec=None):
"""
Wait for process to finish or for specified number of
milliseconds to elapse.
"""
if mSec is None:
mSec = win32event.INFINITE
return win32event.WaitForSingleObject(self.hProcess, mSec)
def kill(self, gracePeriod=5000):
"""
Kill process. Try for an orderly shutdown via WM_CLOSE. If
still running after gracePeriod (5 sec. default), terminate.
"""
win32gui.EnumWindows(self.__close__, 0)
if self.wait(gracePeriod) != win32event.WAIT_OBJECT_0:
win32process.TerminateProcess(self.hProcess, 0)
win32api.Sleep(100) # wait for resources to be released
def __close__(self, hwnd, dummy):
"""
EnumWindows callback - sends WM_CLOSE to any window
owned by this process.
"""
TId, PId = win32process.GetWindowThreadProcessId(hwnd)
if PId == self.PId:
win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0)
def exitCode(self):
"""
Return process exit code.
"""
return win32process.GetExitCodeProcess(self.hProcess)
def run(cmd, mSec=None, stdin=None, stdout=None, stderr=None, **kw):
"""
Run cmd as a child process and return exit code.
mSec: terminate cmd after specified number of milliseconds
stdin, stdout, stderr:
file objects for child I/O (use hStdin etc. to attach
handles instead of files); default is caller's stdin,
stdout & stderr;
kw: see Process.__init__ for more keyword options
"""
if stdin is not None:
kw['hStdin'] = msvcrt.get_osfhandle(stdin.fileno())
if stdout is not None:
kw['hStdout'] = msvcrt.get_osfhandle(stdout.fileno())
if stderr is not None:
kw['hStderr'] = msvcrt.get_osfhandle(stderr.fileno())
child = Process(cmd, **kw)
if child.wait(mSec) != win32event.WAIT_OBJECT_0:
child.kill()
raise WindowsError, 'process timeout exceeded'
return child.exitCode()
if __name__ == '__main__':
# Pipe commands to a shell and display the output in notepad
print 'Testing winprocess.py...'
import tempfile
timeoutSeconds = 15
cmdString = """\
REM Test of winprocess.py piping commands to a shell.\r
REM This window will close in %d seconds.\r
vol\r
net user\r
_this_is_a_test_of_stderr_\r
""" % timeoutSeconds
cmd, out = tempfile.TemporaryFile(), tempfile.TemporaryFile()
cmd.write(cmdString)
cmd.seek(0)
print 'CMD.EXE exit code:', run('cmd.exe', show=0, stdin=cmd,
stdout=out, stderr=out)
cmd.close()
print 'NOTEPAD exit code:', run('notepad.exe %s' % out.file.name,
show=win32con.SW_MAXIMIZE,
mSec=timeoutSeconds*1000)
out.close()
<|fim▁end|> | si.lpDesktop = desktop |
<|file_name|>winprocess.py<|end_file_name|><|fim▁begin|>"""
Windows Process Control
winprocess.run launches a child process and returns the exit code.
Optionally, it can:
redirect stdin, stdout & stderr to files
run the command as another user
limit the process's running time
control the process window (location, size, window state, desktop)
Works on Windows NT, 2000 & XP. Requires Mark Hammond's win32
extensions.
This code is free for any purpose, with no warranty of any kind.
-- John B. Dell'Aquila <[email protected]>
"""
import win32api, win32process, win32security
import win32event, win32con, msvcrt, win32gui
def logonUser(loginString):
"""
Login as specified user and return handle.
loginString: 'Domain\nUser\nPassword'; for local
login use . or empty string as domain
e.g. '.\nadministrator\nsecret_password'
"""
domain, user, passwd = loginString.split('\n')
return win32security.LogonUser(
user,
domain,
passwd,
win32con.LOGON32_LOGON_INTERACTIVE,
win32con.LOGON32_PROVIDER_DEFAULT
)
class Process:
"""
A Windows process.
"""
def __init__(self, cmd, login=None,
hStdin=None, hStdout=None, hStderr=None,
show=1, xy=None, xySize=None,
desktop=None):
"""
Create a Windows process.
cmd: command to run
login: run as user 'Domain\nUser\nPassword'
hStdin, hStdout, hStderr:
handles for process I/O; default is caller's stdin,
stdout & stderr
show: wShowWindow (0=SW_HIDE, 1=SW_NORMAL, ...)
xy: window offset (x, y) of upper left corner in pixels
xySize: window size (width, height) in pixels
desktop: lpDesktop - name of desktop e.g. 'winsta0\\default'
None = inherit current desktop
'' = create new desktop if necessary
User calling login requires additional privileges:
Act as part of the operating system [not needed on Windows XP]
Increase quotas
Replace a process level token
Login string must EITHER be an administrator's account
(ordinary user can't access current desktop - see Microsoft
Q165194) OR use desktop='' to run another desktop invisibly
(may be very slow to startup & finalize).
"""
si = win32process.STARTUPINFO()
si.dwFlags = (win32con.STARTF_USESTDHANDLES ^
win32con.STARTF_USESHOWWINDOW)
if hStdin is None:
si.hStdInput = win32api.GetStdHandle(win32api.STD_INPUT_HANDLE)
else:
si.hStdInput = hStdin
if hStdout is None:
si.hStdOutput = win32api.GetStdHandle(win32api.STD_OUTPUT_HANDLE)
else:
si.hStdOutput = hStdout
if hStderr is None:
si.hStdError = win32api.GetStdHandle(win32api.STD_ERROR_HANDLE)
else:
si.hStdError = hStderr
si.wShowWindow = show
if xy is not None:
si.dwX, si.dwY = xy
si.dwFlags ^= win32con.STARTF_USEPOSITION
if xySize is not None:
si.dwXSize, si.dwYSize = xySize
si.dwFlags ^= win32con.STARTF_USESIZE
if desktop is not None:
si.lpDesktop = desktop
procArgs = (None, # appName
cmd, # commandLine
None, # processAttributes
None, # threadAttributes
1, # bInheritHandles
win32process.CREATE_NEW_CONSOLE, # dwCreationFlags
None, # newEnvironment
None, # currentDirectory
si) # startupinfo
if login is not None:
<|fim_middle|>
else:
procHandles = win32process.CreateProcess(*procArgs)
self.hProcess, self.hThread, self.PId, self.TId = procHandles
def wait(self, mSec=None):
"""
Wait for process to finish or for specified number of
milliseconds to elapse.
"""
if mSec is None:
mSec = win32event.INFINITE
return win32event.WaitForSingleObject(self.hProcess, mSec)
def kill(self, gracePeriod=5000):
"""
Kill process. Try for an orderly shutdown via WM_CLOSE. If
still running after gracePeriod (5 sec. default), terminate.
"""
win32gui.EnumWindows(self.__close__, 0)
if self.wait(gracePeriod) != win32event.WAIT_OBJECT_0:
win32process.TerminateProcess(self.hProcess, 0)
win32api.Sleep(100) # wait for resources to be released
def __close__(self, hwnd, dummy):
"""
EnumWindows callback - sends WM_CLOSE to any window
owned by this process.
"""
TId, PId = win32process.GetWindowThreadProcessId(hwnd)
if PId == self.PId:
win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0)
def exitCode(self):
"""
Return process exit code.
"""
return win32process.GetExitCodeProcess(self.hProcess)
def run(cmd, mSec=None, stdin=None, stdout=None, stderr=None, **kw):
"""
Run cmd as a child process and return exit code.
mSec: terminate cmd after specified number of milliseconds
stdin, stdout, stderr:
file objects for child I/O (use hStdin etc. to attach
handles instead of files); default is caller's stdin,
stdout & stderr;
kw: see Process.__init__ for more keyword options
"""
if stdin is not None:
kw['hStdin'] = msvcrt.get_osfhandle(stdin.fileno())
if stdout is not None:
kw['hStdout'] = msvcrt.get_osfhandle(stdout.fileno())
if stderr is not None:
kw['hStderr'] = msvcrt.get_osfhandle(stderr.fileno())
child = Process(cmd, **kw)
if child.wait(mSec) != win32event.WAIT_OBJECT_0:
child.kill()
raise WindowsError, 'process timeout exceeded'
return child.exitCode()
if __name__ == '__main__':
# Pipe commands to a shell and display the output in notepad
print 'Testing winprocess.py...'
import tempfile
timeoutSeconds = 15
cmdString = """\
REM Test of winprocess.py piping commands to a shell.\r
REM This window will close in %d seconds.\r
vol\r
net user\r
_this_is_a_test_of_stderr_\r
""" % timeoutSeconds
cmd, out = tempfile.TemporaryFile(), tempfile.TemporaryFile()
cmd.write(cmdString)
cmd.seek(0)
print 'CMD.EXE exit code:', run('cmd.exe', show=0, stdin=cmd,
stdout=out, stderr=out)
cmd.close()
print 'NOTEPAD exit code:', run('notepad.exe %s' % out.file.name,
show=win32con.SW_MAXIMIZE,
mSec=timeoutSeconds*1000)
out.close()
<|fim▁end|> | hUser = logonUser(login)
win32security.ImpersonateLoggedOnUser(hUser)
procHandles = win32process.CreateProcessAsUser(hUser, *procArgs)
win32security.RevertToSelf() |
<|file_name|>winprocess.py<|end_file_name|><|fim▁begin|>"""
Windows Process Control
winprocess.run launches a child process and returns the exit code.
Optionally, it can:
redirect stdin, stdout & stderr to files
run the command as another user
limit the process's running time
control the process window (location, size, window state, desktop)
Works on Windows NT, 2000 & XP. Requires Mark Hammond's win32
extensions.
This code is free for any purpose, with no warranty of any kind.
-- John B. Dell'Aquila <[email protected]>
"""
import win32api, win32process, win32security
import win32event, win32con, msvcrt, win32gui
def logonUser(loginString):
"""
Login as specified user and return handle.
loginString: 'Domain\nUser\nPassword'; for local
login use . or empty string as domain
e.g. '.\nadministrator\nsecret_password'
"""
domain, user, passwd = loginString.split('\n')
return win32security.LogonUser(
user,
domain,
passwd,
win32con.LOGON32_LOGON_INTERACTIVE,
win32con.LOGON32_PROVIDER_DEFAULT
)
class Process:
"""
A Windows process.
"""
def __init__(self, cmd, login=None,
hStdin=None, hStdout=None, hStderr=None,
show=1, xy=None, xySize=None,
desktop=None):
"""
Create a Windows process.
cmd: command to run
login: run as user 'Domain\nUser\nPassword'
hStdin, hStdout, hStderr:
handles for process I/O; default is caller's stdin,
stdout & stderr
show: wShowWindow (0=SW_HIDE, 1=SW_NORMAL, ...)
xy: window offset (x, y) of upper left corner in pixels
xySize: window size (width, height) in pixels
desktop: lpDesktop - name of desktop e.g. 'winsta0\\default'
None = inherit current desktop
'' = create new desktop if necessary
User calling login requires additional privileges:
Act as part of the operating system [not needed on Windows XP]
Increase quotas
Replace a process level token
Login string must EITHER be an administrator's account
(ordinary user can't access current desktop - see Microsoft
Q165194) OR use desktop='' to run another desktop invisibly
(may be very slow to startup & finalize).
"""
si = win32process.STARTUPINFO()
si.dwFlags = (win32con.STARTF_USESTDHANDLES ^
win32con.STARTF_USESHOWWINDOW)
if hStdin is None:
si.hStdInput = win32api.GetStdHandle(win32api.STD_INPUT_HANDLE)
else:
si.hStdInput = hStdin
if hStdout is None:
si.hStdOutput = win32api.GetStdHandle(win32api.STD_OUTPUT_HANDLE)
else:
si.hStdOutput = hStdout
if hStderr is None:
si.hStdError = win32api.GetStdHandle(win32api.STD_ERROR_HANDLE)
else:
si.hStdError = hStderr
si.wShowWindow = show
if xy is not None:
si.dwX, si.dwY = xy
si.dwFlags ^= win32con.STARTF_USEPOSITION
if xySize is not None:
si.dwXSize, si.dwYSize = xySize
si.dwFlags ^= win32con.STARTF_USESIZE
if desktop is not None:
si.lpDesktop = desktop
procArgs = (None, # appName
cmd, # commandLine
None, # processAttributes
None, # threadAttributes
1, # bInheritHandles
win32process.CREATE_NEW_CONSOLE, # dwCreationFlags
None, # newEnvironment
None, # currentDirectory
si) # startupinfo
if login is not None:
hUser = logonUser(login)
win32security.ImpersonateLoggedOnUser(hUser)
procHandles = win32process.CreateProcessAsUser(hUser, *procArgs)
win32security.RevertToSelf()
else:
<|fim_middle|>
self.hProcess, self.hThread, self.PId, self.TId = procHandles
def wait(self, mSec=None):
"""
Wait for process to finish or for specified number of
milliseconds to elapse.
"""
if mSec is None:
mSec = win32event.INFINITE
return win32event.WaitForSingleObject(self.hProcess, mSec)
def kill(self, gracePeriod=5000):
"""
Kill process. Try for an orderly shutdown via WM_CLOSE. If
still running after gracePeriod (5 sec. default), terminate.
"""
win32gui.EnumWindows(self.__close__, 0)
if self.wait(gracePeriod) != win32event.WAIT_OBJECT_0:
win32process.TerminateProcess(self.hProcess, 0)
win32api.Sleep(100) # wait for resources to be released
def __close__(self, hwnd, dummy):
"""
EnumWindows callback - sends WM_CLOSE to any window
owned by this process.
"""
TId, PId = win32process.GetWindowThreadProcessId(hwnd)
if PId == self.PId:
win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0)
def exitCode(self):
"""
Return process exit code.
"""
return win32process.GetExitCodeProcess(self.hProcess)
def run(cmd, mSec=None, stdin=None, stdout=None, stderr=None, **kw):
"""
Run cmd as a child process and return exit code.
mSec: terminate cmd after specified number of milliseconds
stdin, stdout, stderr:
file objects for child I/O (use hStdin etc. to attach
handles instead of files); default is caller's stdin,
stdout & stderr;
kw: see Process.__init__ for more keyword options
"""
if stdin is not None:
kw['hStdin'] = msvcrt.get_osfhandle(stdin.fileno())
if stdout is not None:
kw['hStdout'] = msvcrt.get_osfhandle(stdout.fileno())
if stderr is not None:
kw['hStderr'] = msvcrt.get_osfhandle(stderr.fileno())
child = Process(cmd, **kw)
if child.wait(mSec) != win32event.WAIT_OBJECT_0:
child.kill()
raise WindowsError, 'process timeout exceeded'
return child.exitCode()
if __name__ == '__main__':
# Pipe commands to a shell and display the output in notepad
print 'Testing winprocess.py...'
import tempfile
timeoutSeconds = 15
cmdString = """\
REM Test of winprocess.py piping commands to a shell.\r
REM This window will close in %d seconds.\r
vol\r
net user\r
_this_is_a_test_of_stderr_\r
""" % timeoutSeconds
cmd, out = tempfile.TemporaryFile(), tempfile.TemporaryFile()
cmd.write(cmdString)
cmd.seek(0)
print 'CMD.EXE exit code:', run('cmd.exe', show=0, stdin=cmd,
stdout=out, stderr=out)
cmd.close()
print 'NOTEPAD exit code:', run('notepad.exe %s' % out.file.name,
show=win32con.SW_MAXIMIZE,
mSec=timeoutSeconds*1000)
out.close()
<|fim▁end|> | procHandles = win32process.CreateProcess(*procArgs) |
<|file_name|>winprocess.py<|end_file_name|><|fim▁begin|>"""
Windows Process Control
winprocess.run launches a child process and returns the exit code.
Optionally, it can:
redirect stdin, stdout & stderr to files
run the command as another user
limit the process's running time
control the process window (location, size, window state, desktop)
Works on Windows NT, 2000 & XP. Requires Mark Hammond's win32
extensions.
This code is free for any purpose, with no warranty of any kind.
-- John B. Dell'Aquila <[email protected]>
"""
import win32api, win32process, win32security
import win32event, win32con, msvcrt, win32gui
def logonUser(loginString):
"""
Login as specified user and return handle.
loginString: 'Domain\nUser\nPassword'; for local
login use . or empty string as domain
e.g. '.\nadministrator\nsecret_password'
"""
domain, user, passwd = loginString.split('\n')
return win32security.LogonUser(
user,
domain,
passwd,
win32con.LOGON32_LOGON_INTERACTIVE,
win32con.LOGON32_PROVIDER_DEFAULT
)
class Process:
"""
A Windows process.
"""
def __init__(self, cmd, login=None,
hStdin=None, hStdout=None, hStderr=None,
show=1, xy=None, xySize=None,
desktop=None):
"""
Create a Windows process.
cmd: command to run
login: run as user 'Domain\nUser\nPassword'
hStdin, hStdout, hStderr:
handles for process I/O; default is caller's stdin,
stdout & stderr
show: wShowWindow (0=SW_HIDE, 1=SW_NORMAL, ...)
xy: window offset (x, y) of upper left corner in pixels
xySize: window size (width, height) in pixels
desktop: lpDesktop - name of desktop e.g. 'winsta0\\default'
None = inherit current desktop
'' = create new desktop if necessary
User calling login requires additional privileges:
Act as part of the operating system [not needed on Windows XP]
Increase quotas
Replace a process level token
Login string must EITHER be an administrator's account
(ordinary user can't access current desktop - see Microsoft
Q165194) OR use desktop='' to run another desktop invisibly
(may be very slow to startup & finalize).
"""
si = win32process.STARTUPINFO()
si.dwFlags = (win32con.STARTF_USESTDHANDLES ^
win32con.STARTF_USESHOWWINDOW)
if hStdin is None:
si.hStdInput = win32api.GetStdHandle(win32api.STD_INPUT_HANDLE)
else:
si.hStdInput = hStdin
if hStdout is None:
si.hStdOutput = win32api.GetStdHandle(win32api.STD_OUTPUT_HANDLE)
else:
si.hStdOutput = hStdout
if hStderr is None:
si.hStdError = win32api.GetStdHandle(win32api.STD_ERROR_HANDLE)
else:
si.hStdError = hStderr
si.wShowWindow = show
if xy is not None:
si.dwX, si.dwY = xy
si.dwFlags ^= win32con.STARTF_USEPOSITION
if xySize is not None:
si.dwXSize, si.dwYSize = xySize
si.dwFlags ^= win32con.STARTF_USESIZE
if desktop is not None:
si.lpDesktop = desktop
procArgs = (None, # appName
cmd, # commandLine
None, # processAttributes
None, # threadAttributes
1, # bInheritHandles
win32process.CREATE_NEW_CONSOLE, # dwCreationFlags
None, # newEnvironment
None, # currentDirectory
si) # startupinfo
if login is not None:
hUser = logonUser(login)
win32security.ImpersonateLoggedOnUser(hUser)
procHandles = win32process.CreateProcessAsUser(hUser, *procArgs)
win32security.RevertToSelf()
else:
procHandles = win32process.CreateProcess(*procArgs)
self.hProcess, self.hThread, self.PId, self.TId = procHandles
def wait(self, mSec=None):
"""
Wait for process to finish or for specified number of
milliseconds to elapse.
"""
if mSec is None:
<|fim_middle|>
return win32event.WaitForSingleObject(self.hProcess, mSec)
def kill(self, gracePeriod=5000):
"""
Kill process. Try for an orderly shutdown via WM_CLOSE. If
still running after gracePeriod (5 sec. default), terminate.
"""
win32gui.EnumWindows(self.__close__, 0)
if self.wait(gracePeriod) != win32event.WAIT_OBJECT_0:
win32process.TerminateProcess(self.hProcess, 0)
win32api.Sleep(100) # wait for resources to be released
def __close__(self, hwnd, dummy):
"""
EnumWindows callback - sends WM_CLOSE to any window
owned by this process.
"""
TId, PId = win32process.GetWindowThreadProcessId(hwnd)
if PId == self.PId:
win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0)
def exitCode(self):
"""
Return process exit code.
"""
return win32process.GetExitCodeProcess(self.hProcess)
def run(cmd, mSec=None, stdin=None, stdout=None, stderr=None, **kw):
"""
Run cmd as a child process and return exit code.
mSec: terminate cmd after specified number of milliseconds
stdin, stdout, stderr:
file objects for child I/O (use hStdin etc. to attach
handles instead of files); default is caller's stdin,
stdout & stderr;
kw: see Process.__init__ for more keyword options
"""
if stdin is not None:
kw['hStdin'] = msvcrt.get_osfhandle(stdin.fileno())
if stdout is not None:
kw['hStdout'] = msvcrt.get_osfhandle(stdout.fileno())
if stderr is not None:
kw['hStderr'] = msvcrt.get_osfhandle(stderr.fileno())
child = Process(cmd, **kw)
if child.wait(mSec) != win32event.WAIT_OBJECT_0:
child.kill()
raise WindowsError, 'process timeout exceeded'
return child.exitCode()
if __name__ == '__main__':
# Pipe commands to a shell and display the output in notepad
print 'Testing winprocess.py...'
import tempfile
timeoutSeconds = 15
cmdString = """\
REM Test of winprocess.py piping commands to a shell.\r
REM This window will close in %d seconds.\r
vol\r
net user\r
_this_is_a_test_of_stderr_\r
""" % timeoutSeconds
cmd, out = tempfile.TemporaryFile(), tempfile.TemporaryFile()
cmd.write(cmdString)
cmd.seek(0)
print 'CMD.EXE exit code:', run('cmd.exe', show=0, stdin=cmd,
stdout=out, stderr=out)
cmd.close()
print 'NOTEPAD exit code:', run('notepad.exe %s' % out.file.name,
show=win32con.SW_MAXIMIZE,
mSec=timeoutSeconds*1000)
out.close()
<|fim▁end|> | mSec = win32event.INFINITE |
<|file_name|>winprocess.py<|end_file_name|><|fim▁begin|>"""
Windows Process Control
winprocess.run launches a child process and returns the exit code.
Optionally, it can:
redirect stdin, stdout & stderr to files
run the command as another user
limit the process's running time
control the process window (location, size, window state, desktop)
Works on Windows NT, 2000 & XP. Requires Mark Hammond's win32
extensions.
This code is free for any purpose, with no warranty of any kind.
-- John B. Dell'Aquila <[email protected]>
"""
import win32api, win32process, win32security
import win32event, win32con, msvcrt, win32gui
def logonUser(loginString):
"""
Login as specified user and return handle.
loginString: 'Domain\nUser\nPassword'; for local
login use . or empty string as domain
e.g. '.\nadministrator\nsecret_password'
"""
domain, user, passwd = loginString.split('\n')
return win32security.LogonUser(
user,
domain,
passwd,
win32con.LOGON32_LOGON_INTERACTIVE,
win32con.LOGON32_PROVIDER_DEFAULT
)
class Process:
"""
A Windows process.
"""
def __init__(self, cmd, login=None,
hStdin=None, hStdout=None, hStderr=None,
show=1, xy=None, xySize=None,
desktop=None):
"""
Create a Windows process.
cmd: command to run
login: run as user 'Domain\nUser\nPassword'
hStdin, hStdout, hStderr:
handles for process I/O; default is caller's stdin,
stdout & stderr
show: wShowWindow (0=SW_HIDE, 1=SW_NORMAL, ...)
xy: window offset (x, y) of upper left corner in pixels
xySize: window size (width, height) in pixels
desktop: lpDesktop - name of desktop e.g. 'winsta0\\default'
None = inherit current desktop
'' = create new desktop if necessary
User calling login requires additional privileges:
Act as part of the operating system [not needed on Windows XP]
Increase quotas
Replace a process level token
Login string must EITHER be an administrator's account
(ordinary user can't access current desktop - see Microsoft
Q165194) OR use desktop='' to run another desktop invisibly
(may be very slow to startup & finalize).
"""
si = win32process.STARTUPINFO()
si.dwFlags = (win32con.STARTF_USESTDHANDLES ^
win32con.STARTF_USESHOWWINDOW)
if hStdin is None:
si.hStdInput = win32api.GetStdHandle(win32api.STD_INPUT_HANDLE)
else:
si.hStdInput = hStdin
if hStdout is None:
si.hStdOutput = win32api.GetStdHandle(win32api.STD_OUTPUT_HANDLE)
else:
si.hStdOutput = hStdout
if hStderr is None:
si.hStdError = win32api.GetStdHandle(win32api.STD_ERROR_HANDLE)
else:
si.hStdError = hStderr
si.wShowWindow = show
if xy is not None:
si.dwX, si.dwY = xy
si.dwFlags ^= win32con.STARTF_USEPOSITION
if xySize is not None:
si.dwXSize, si.dwYSize = xySize
si.dwFlags ^= win32con.STARTF_USESIZE
if desktop is not None:
si.lpDesktop = desktop
procArgs = (None, # appName
cmd, # commandLine
None, # processAttributes
None, # threadAttributes
1, # bInheritHandles
win32process.CREATE_NEW_CONSOLE, # dwCreationFlags
None, # newEnvironment
None, # currentDirectory
si) # startupinfo
if login is not None:
hUser = logonUser(login)
win32security.ImpersonateLoggedOnUser(hUser)
procHandles = win32process.CreateProcessAsUser(hUser, *procArgs)
win32security.RevertToSelf()
else:
procHandles = win32process.CreateProcess(*procArgs)
self.hProcess, self.hThread, self.PId, self.TId = procHandles
def wait(self, mSec=None):
"""
Wait for process to finish or for specified number of
milliseconds to elapse.
"""
if mSec is None:
mSec = win32event.INFINITE
return win32event.WaitForSingleObject(self.hProcess, mSec)
def kill(self, gracePeriod=5000):
"""
Kill process. Try for an orderly shutdown via WM_CLOSE. If
still running after gracePeriod (5 sec. default), terminate.
"""
win32gui.EnumWindows(self.__close__, 0)
if self.wait(gracePeriod) != win32event.WAIT_OBJECT_0:
<|fim_middle|>
def __close__(self, hwnd, dummy):
"""
EnumWindows callback - sends WM_CLOSE to any window
owned by this process.
"""
TId, PId = win32process.GetWindowThreadProcessId(hwnd)
if PId == self.PId:
win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0)
def exitCode(self):
"""
Return process exit code.
"""
return win32process.GetExitCodeProcess(self.hProcess)
def run(cmd, mSec=None, stdin=None, stdout=None, stderr=None, **kw):
"""
Run cmd as a child process and return exit code.
mSec: terminate cmd after specified number of milliseconds
stdin, stdout, stderr:
file objects for child I/O (use hStdin etc. to attach
handles instead of files); default is caller's stdin,
stdout & stderr;
kw: see Process.__init__ for more keyword options
"""
if stdin is not None:
kw['hStdin'] = msvcrt.get_osfhandle(stdin.fileno())
if stdout is not None:
kw['hStdout'] = msvcrt.get_osfhandle(stdout.fileno())
if stderr is not None:
kw['hStderr'] = msvcrt.get_osfhandle(stderr.fileno())
child = Process(cmd, **kw)
if child.wait(mSec) != win32event.WAIT_OBJECT_0:
child.kill()
raise WindowsError, 'process timeout exceeded'
return child.exitCode()
if __name__ == '__main__':
# Pipe commands to a shell and display the output in notepad
print 'Testing winprocess.py...'
import tempfile
timeoutSeconds = 15
cmdString = """\
REM Test of winprocess.py piping commands to a shell.\r
REM This window will close in %d seconds.\r
vol\r
net user\r
_this_is_a_test_of_stderr_\r
""" % timeoutSeconds
cmd, out = tempfile.TemporaryFile(), tempfile.TemporaryFile()
cmd.write(cmdString)
cmd.seek(0)
print 'CMD.EXE exit code:', run('cmd.exe', show=0, stdin=cmd,
stdout=out, stderr=out)
cmd.close()
print 'NOTEPAD exit code:', run('notepad.exe %s' % out.file.name,
show=win32con.SW_MAXIMIZE,
mSec=timeoutSeconds*1000)
out.close()
<|fim▁end|> | win32process.TerminateProcess(self.hProcess, 0)
win32api.Sleep(100) # wait for resources to be released |
<|file_name|>winprocess.py<|end_file_name|><|fim▁begin|>"""
Windows Process Control
winprocess.run launches a child process and returns the exit code.
Optionally, it can:
redirect stdin, stdout & stderr to files
run the command as another user
limit the process's running time
control the process window (location, size, window state, desktop)
Works on Windows NT, 2000 & XP. Requires Mark Hammond's win32
extensions.
This code is free for any purpose, with no warranty of any kind.
-- John B. Dell'Aquila <[email protected]>
"""
import win32api, win32process, win32security
import win32event, win32con, msvcrt, win32gui
def logonUser(loginString):
"""
Login as specified user and return handle.
loginString: 'Domain\nUser\nPassword'; for local
login use . or empty string as domain
e.g. '.\nadministrator\nsecret_password'
"""
domain, user, passwd = loginString.split('\n')
return win32security.LogonUser(
user,
domain,
passwd,
win32con.LOGON32_LOGON_INTERACTIVE,
win32con.LOGON32_PROVIDER_DEFAULT
)
class Process:
"""
A Windows process.
"""
def __init__(self, cmd, login=None,
hStdin=None, hStdout=None, hStderr=None,
show=1, xy=None, xySize=None,
desktop=None):
"""
Create a Windows process.
cmd: command to run
login: run as user 'Domain\nUser\nPassword'
hStdin, hStdout, hStderr:
handles for process I/O; default is caller's stdin,
stdout & stderr
show: wShowWindow (0=SW_HIDE, 1=SW_NORMAL, ...)
xy: window offset (x, y) of upper left corner in pixels
xySize: window size (width, height) in pixels
desktop: lpDesktop - name of desktop e.g. 'winsta0\\default'
None = inherit current desktop
'' = create new desktop if necessary
User calling login requires additional privileges:
Act as part of the operating system [not needed on Windows XP]
Increase quotas
Replace a process level token
Login string must EITHER be an administrator's account
(ordinary user can't access current desktop - see Microsoft
Q165194) OR use desktop='' to run another desktop invisibly
(may be very slow to startup & finalize).
"""
si = win32process.STARTUPINFO()
si.dwFlags = (win32con.STARTF_USESTDHANDLES ^
win32con.STARTF_USESHOWWINDOW)
if hStdin is None:
si.hStdInput = win32api.GetStdHandle(win32api.STD_INPUT_HANDLE)
else:
si.hStdInput = hStdin
if hStdout is None:
si.hStdOutput = win32api.GetStdHandle(win32api.STD_OUTPUT_HANDLE)
else:
si.hStdOutput = hStdout
if hStderr is None:
si.hStdError = win32api.GetStdHandle(win32api.STD_ERROR_HANDLE)
else:
si.hStdError = hStderr
si.wShowWindow = show
if xy is not None:
si.dwX, si.dwY = xy
si.dwFlags ^= win32con.STARTF_USEPOSITION
if xySize is not None:
si.dwXSize, si.dwYSize = xySize
si.dwFlags ^= win32con.STARTF_USESIZE
if desktop is not None:
si.lpDesktop = desktop
procArgs = (None, # appName
cmd, # commandLine
None, # processAttributes
None, # threadAttributes
1, # bInheritHandles
win32process.CREATE_NEW_CONSOLE, # dwCreationFlags
None, # newEnvironment
None, # currentDirectory
si) # startupinfo
if login is not None:
hUser = logonUser(login)
win32security.ImpersonateLoggedOnUser(hUser)
procHandles = win32process.CreateProcessAsUser(hUser, *procArgs)
win32security.RevertToSelf()
else:
procHandles = win32process.CreateProcess(*procArgs)
self.hProcess, self.hThread, self.PId, self.TId = procHandles
def wait(self, mSec=None):
"""
Wait for process to finish or for specified number of
milliseconds to elapse.
"""
if mSec is None:
mSec = win32event.INFINITE
return win32event.WaitForSingleObject(self.hProcess, mSec)
def kill(self, gracePeriod=5000):
"""
Kill process. Try for an orderly shutdown via WM_CLOSE. If
still running after gracePeriod (5 sec. default), terminate.
"""
win32gui.EnumWindows(self.__close__, 0)
if self.wait(gracePeriod) != win32event.WAIT_OBJECT_0:
win32process.TerminateProcess(self.hProcess, 0)
win32api.Sleep(100) # wait for resources to be released
def __close__(self, hwnd, dummy):
"""
EnumWindows callback - sends WM_CLOSE to any window
owned by this process.
"""
TId, PId = win32process.GetWindowThreadProcessId(hwnd)
if PId == self.PId:
<|fim_middle|>
def exitCode(self):
"""
Return process exit code.
"""
return win32process.GetExitCodeProcess(self.hProcess)
def run(cmd, mSec=None, stdin=None, stdout=None, stderr=None, **kw):
"""
Run cmd as a child process and return exit code.
mSec: terminate cmd after specified number of milliseconds
stdin, stdout, stderr:
file objects for child I/O (use hStdin etc. to attach
handles instead of files); default is caller's stdin,
stdout & stderr;
kw: see Process.__init__ for more keyword options
"""
if stdin is not None:
kw['hStdin'] = msvcrt.get_osfhandle(stdin.fileno())
if stdout is not None:
kw['hStdout'] = msvcrt.get_osfhandle(stdout.fileno())
if stderr is not None:
kw['hStderr'] = msvcrt.get_osfhandle(stderr.fileno())
child = Process(cmd, **kw)
if child.wait(mSec) != win32event.WAIT_OBJECT_0:
child.kill()
raise WindowsError, 'process timeout exceeded'
return child.exitCode()
if __name__ == '__main__':
# Pipe commands to a shell and display the output in notepad
print 'Testing winprocess.py...'
import tempfile
timeoutSeconds = 15
cmdString = """\
REM Test of winprocess.py piping commands to a shell.\r
REM This window will close in %d seconds.\r
vol\r
net user\r
_this_is_a_test_of_stderr_\r
""" % timeoutSeconds
cmd, out = tempfile.TemporaryFile(), tempfile.TemporaryFile()
cmd.write(cmdString)
cmd.seek(0)
print 'CMD.EXE exit code:', run('cmd.exe', show=0, stdin=cmd,
stdout=out, stderr=out)
cmd.close()
print 'NOTEPAD exit code:', run('notepad.exe %s' % out.file.name,
show=win32con.SW_MAXIMIZE,
mSec=timeoutSeconds*1000)
out.close()
<|fim▁end|> | win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0) |
<|file_name|>winprocess.py<|end_file_name|><|fim▁begin|>"""
Windows Process Control
winprocess.run launches a child process and returns the exit code.
Optionally, it can:
redirect stdin, stdout & stderr to files
run the command as another user
limit the process's running time
control the process window (location, size, window state, desktop)
Works on Windows NT, 2000 & XP. Requires Mark Hammond's win32
extensions.
This code is free for any purpose, with no warranty of any kind.
-- John B. Dell'Aquila <[email protected]>
"""
import win32api, win32process, win32security
import win32event, win32con, msvcrt, win32gui
def logonUser(loginString):
"""
Login as specified user and return handle.
loginString: 'Domain\nUser\nPassword'; for local
login use . or empty string as domain
e.g. '.\nadministrator\nsecret_password'
"""
domain, user, passwd = loginString.split('\n')
return win32security.LogonUser(
user,
domain,
passwd,
win32con.LOGON32_LOGON_INTERACTIVE,
win32con.LOGON32_PROVIDER_DEFAULT
)
class Process:
"""
A Windows process.
"""
def __init__(self, cmd, login=None,
hStdin=None, hStdout=None, hStderr=None,
show=1, xy=None, xySize=None,
desktop=None):
"""
Create a Windows process.
cmd: command to run
login: run as user 'Domain\nUser\nPassword'
hStdin, hStdout, hStderr:
handles for process I/O; default is caller's stdin,
stdout & stderr
show: wShowWindow (0=SW_HIDE, 1=SW_NORMAL, ...)
xy: window offset (x, y) of upper left corner in pixels
xySize: window size (width, height) in pixels
desktop: lpDesktop - name of desktop e.g. 'winsta0\\default'
None = inherit current desktop
'' = create new desktop if necessary
User calling login requires additional privileges:
Act as part of the operating system [not needed on Windows XP]
Increase quotas
Replace a process level token
Login string must EITHER be an administrator's account
(ordinary user can't access current desktop - see Microsoft
Q165194) OR use desktop='' to run another desktop invisibly
(may be very slow to startup & finalize).
"""
si = win32process.STARTUPINFO()
si.dwFlags = (win32con.STARTF_USESTDHANDLES ^
win32con.STARTF_USESHOWWINDOW)
if hStdin is None:
si.hStdInput = win32api.GetStdHandle(win32api.STD_INPUT_HANDLE)
else:
si.hStdInput = hStdin
if hStdout is None:
si.hStdOutput = win32api.GetStdHandle(win32api.STD_OUTPUT_HANDLE)
else:
si.hStdOutput = hStdout
if hStderr is None:
si.hStdError = win32api.GetStdHandle(win32api.STD_ERROR_HANDLE)
else:
si.hStdError = hStderr
si.wShowWindow = show
if xy is not None:
si.dwX, si.dwY = xy
si.dwFlags ^= win32con.STARTF_USEPOSITION
if xySize is not None:
si.dwXSize, si.dwYSize = xySize
si.dwFlags ^= win32con.STARTF_USESIZE
if desktop is not None:
si.lpDesktop = desktop
procArgs = (None, # appName
cmd, # commandLine
None, # processAttributes
None, # threadAttributes
1, # bInheritHandles
win32process.CREATE_NEW_CONSOLE, # dwCreationFlags
None, # newEnvironment
None, # currentDirectory
si) # startupinfo
if login is not None:
hUser = logonUser(login)
win32security.ImpersonateLoggedOnUser(hUser)
procHandles = win32process.CreateProcessAsUser(hUser, *procArgs)
win32security.RevertToSelf()
else:
procHandles = win32process.CreateProcess(*procArgs)
self.hProcess, self.hThread, self.PId, self.TId = procHandles
def wait(self, mSec=None):
"""
Wait for process to finish or for specified number of
milliseconds to elapse.
"""
if mSec is None:
mSec = win32event.INFINITE
return win32event.WaitForSingleObject(self.hProcess, mSec)
def kill(self, gracePeriod=5000):
"""
Kill process. Try for an orderly shutdown via WM_CLOSE. If
still running after gracePeriod (5 sec. default), terminate.
"""
win32gui.EnumWindows(self.__close__, 0)
if self.wait(gracePeriod) != win32event.WAIT_OBJECT_0:
win32process.TerminateProcess(self.hProcess, 0)
win32api.Sleep(100) # wait for resources to be released
def __close__(self, hwnd, dummy):
"""
EnumWindows callback - sends WM_CLOSE to any window
owned by this process.
"""
TId, PId = win32process.GetWindowThreadProcessId(hwnd)
if PId == self.PId:
win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0)
def exitCode(self):
"""
Return process exit code.
"""
return win32process.GetExitCodeProcess(self.hProcess)
def run(cmd, mSec=None, stdin=None, stdout=None, stderr=None, **kw):
"""
Run cmd as a child process and return exit code.
mSec: terminate cmd after specified number of milliseconds
stdin, stdout, stderr:
file objects for child I/O (use hStdin etc. to attach
handles instead of files); default is caller's stdin,
stdout & stderr;
kw: see Process.__init__ for more keyword options
"""
if stdin is not None:
<|fim_middle|>
if stdout is not None:
kw['hStdout'] = msvcrt.get_osfhandle(stdout.fileno())
if stderr is not None:
kw['hStderr'] = msvcrt.get_osfhandle(stderr.fileno())
child = Process(cmd, **kw)
if child.wait(mSec) != win32event.WAIT_OBJECT_0:
child.kill()
raise WindowsError, 'process timeout exceeded'
return child.exitCode()
if __name__ == '__main__':
# Pipe commands to a shell and display the output in notepad
print 'Testing winprocess.py...'
import tempfile
timeoutSeconds = 15
cmdString = """\
REM Test of winprocess.py piping commands to a shell.\r
REM This window will close in %d seconds.\r
vol\r
net user\r
_this_is_a_test_of_stderr_\r
""" % timeoutSeconds
cmd, out = tempfile.TemporaryFile(), tempfile.TemporaryFile()
cmd.write(cmdString)
cmd.seek(0)
print 'CMD.EXE exit code:', run('cmd.exe', show=0, stdin=cmd,
stdout=out, stderr=out)
cmd.close()
print 'NOTEPAD exit code:', run('notepad.exe %s' % out.file.name,
show=win32con.SW_MAXIMIZE,
mSec=timeoutSeconds*1000)
out.close()
<|fim▁end|> | kw['hStdin'] = msvcrt.get_osfhandle(stdin.fileno()) |
<|file_name|>winprocess.py<|end_file_name|><|fim▁begin|>"""
Windows Process Control
winprocess.run launches a child process and returns the exit code.
Optionally, it can:
redirect stdin, stdout & stderr to files
run the command as another user
limit the process's running time
control the process window (location, size, window state, desktop)
Works on Windows NT, 2000 & XP. Requires Mark Hammond's win32
extensions.
This code is free for any purpose, with no warranty of any kind.
-- John B. Dell'Aquila <[email protected]>
"""
import win32api, win32process, win32security
import win32event, win32con, msvcrt, win32gui
def logonUser(loginString):
"""
Login as specified user and return handle.
loginString: 'Domain\nUser\nPassword'; for local
login use . or empty string as domain
e.g. '.\nadministrator\nsecret_password'
"""
domain, user, passwd = loginString.split('\n')
return win32security.LogonUser(
user,
domain,
passwd,
win32con.LOGON32_LOGON_INTERACTIVE,
win32con.LOGON32_PROVIDER_DEFAULT
)
class Process:
"""
A Windows process.
"""
def __init__(self, cmd, login=None,
hStdin=None, hStdout=None, hStderr=None,
show=1, xy=None, xySize=None,
desktop=None):
"""
Create a Windows process.
cmd: command to run
login: run as user 'Domain\nUser\nPassword'
hStdin, hStdout, hStderr:
handles for process I/O; default is caller's stdin,
stdout & stderr
show: wShowWindow (0=SW_HIDE, 1=SW_NORMAL, ...)
xy: window offset (x, y) of upper left corner in pixels
xySize: window size (width, height) in pixels
desktop: lpDesktop - name of desktop e.g. 'winsta0\\default'
None = inherit current desktop
'' = create new desktop if necessary
User calling login requires additional privileges:
Act as part of the operating system [not needed on Windows XP]
Increase quotas
Replace a process level token
Login string must EITHER be an administrator's account
(ordinary user can't access current desktop - see Microsoft
Q165194) OR use desktop='' to run another desktop invisibly
(may be very slow to startup & finalize).
"""
si = win32process.STARTUPINFO()
si.dwFlags = (win32con.STARTF_USESTDHANDLES ^
win32con.STARTF_USESHOWWINDOW)
if hStdin is None:
si.hStdInput = win32api.GetStdHandle(win32api.STD_INPUT_HANDLE)
else:
si.hStdInput = hStdin
if hStdout is None:
si.hStdOutput = win32api.GetStdHandle(win32api.STD_OUTPUT_HANDLE)
else:
si.hStdOutput = hStdout
if hStderr is None:
si.hStdError = win32api.GetStdHandle(win32api.STD_ERROR_HANDLE)
else:
si.hStdError = hStderr
si.wShowWindow = show
if xy is not None:
si.dwX, si.dwY = xy
si.dwFlags ^= win32con.STARTF_USEPOSITION
if xySize is not None:
si.dwXSize, si.dwYSize = xySize
si.dwFlags ^= win32con.STARTF_USESIZE
if desktop is not None:
si.lpDesktop = desktop
procArgs = (None, # appName
cmd, # commandLine
None, # processAttributes
None, # threadAttributes
1, # bInheritHandles
win32process.CREATE_NEW_CONSOLE, # dwCreationFlags
None, # newEnvironment
None, # currentDirectory
si) # startupinfo
if login is not None:
hUser = logonUser(login)
win32security.ImpersonateLoggedOnUser(hUser)
procHandles = win32process.CreateProcessAsUser(hUser, *procArgs)
win32security.RevertToSelf()
else:
procHandles = win32process.CreateProcess(*procArgs)
self.hProcess, self.hThread, self.PId, self.TId = procHandles
def wait(self, mSec=None):
"""
Wait for process to finish or for specified number of
milliseconds to elapse.
"""
if mSec is None:
mSec = win32event.INFINITE
return win32event.WaitForSingleObject(self.hProcess, mSec)
def kill(self, gracePeriod=5000):
"""
Kill process. Try for an orderly shutdown via WM_CLOSE. If
still running after gracePeriod (5 sec. default), terminate.
"""
win32gui.EnumWindows(self.__close__, 0)
if self.wait(gracePeriod) != win32event.WAIT_OBJECT_0:
win32process.TerminateProcess(self.hProcess, 0)
win32api.Sleep(100) # wait for resources to be released
def __close__(self, hwnd, dummy):
"""
EnumWindows callback - sends WM_CLOSE to any window
owned by this process.
"""
TId, PId = win32process.GetWindowThreadProcessId(hwnd)
if PId == self.PId:
win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0)
def exitCode(self):
"""
Return process exit code.
"""
return win32process.GetExitCodeProcess(self.hProcess)
def run(cmd, mSec=None, stdin=None, stdout=None, stderr=None, **kw):
"""
Run cmd as a child process and return exit code.
mSec: terminate cmd after specified number of milliseconds
stdin, stdout, stderr:
file objects for child I/O (use hStdin etc. to attach
handles instead of files); default is caller's stdin,
stdout & stderr;
kw: see Process.__init__ for more keyword options
"""
if stdin is not None:
kw['hStdin'] = msvcrt.get_osfhandle(stdin.fileno())
if stdout is not None:
<|fim_middle|>
if stderr is not None:
kw['hStderr'] = msvcrt.get_osfhandle(stderr.fileno())
child = Process(cmd, **kw)
if child.wait(mSec) != win32event.WAIT_OBJECT_0:
child.kill()
raise WindowsError, 'process timeout exceeded'
return child.exitCode()
if __name__ == '__main__':
# Pipe commands to a shell and display the output in notepad
print 'Testing winprocess.py...'
import tempfile
timeoutSeconds = 15
cmdString = """\
REM Test of winprocess.py piping commands to a shell.\r
REM This window will close in %d seconds.\r
vol\r
net user\r
_this_is_a_test_of_stderr_\r
""" % timeoutSeconds
cmd, out = tempfile.TemporaryFile(), tempfile.TemporaryFile()
cmd.write(cmdString)
cmd.seek(0)
print 'CMD.EXE exit code:', run('cmd.exe', show=0, stdin=cmd,
stdout=out, stderr=out)
cmd.close()
print 'NOTEPAD exit code:', run('notepad.exe %s' % out.file.name,
show=win32con.SW_MAXIMIZE,
mSec=timeoutSeconds*1000)
out.close()
<|fim▁end|> | kw['hStdout'] = msvcrt.get_osfhandle(stdout.fileno()) |
<|file_name|>winprocess.py<|end_file_name|><|fim▁begin|>"""
Windows Process Control
winprocess.run launches a child process and returns the exit code.
Optionally, it can:
redirect stdin, stdout & stderr to files
run the command as another user
limit the process's running time
control the process window (location, size, window state, desktop)
Works on Windows NT, 2000 & XP. Requires Mark Hammond's win32
extensions.
This code is free for any purpose, with no warranty of any kind.
-- John B. Dell'Aquila <[email protected]>
"""
import win32api, win32process, win32security
import win32event, win32con, msvcrt, win32gui
def logonUser(loginString):
"""
Login as specified user and return handle.
loginString: 'Domain\nUser\nPassword'; for local
login use . or empty string as domain
e.g. '.\nadministrator\nsecret_password'
"""
domain, user, passwd = loginString.split('\n')
return win32security.LogonUser(
user,
domain,
passwd,
win32con.LOGON32_LOGON_INTERACTIVE,
win32con.LOGON32_PROVIDER_DEFAULT
)
class Process:
"""
A Windows process.
"""
def __init__(self, cmd, login=None,
hStdin=None, hStdout=None, hStderr=None,
show=1, xy=None, xySize=None,
desktop=None):
"""
Create a Windows process.
cmd: command to run
login: run as user 'Domain\nUser\nPassword'
hStdin, hStdout, hStderr:
handles for process I/O; default is caller's stdin,
stdout & stderr
show: wShowWindow (0=SW_HIDE, 1=SW_NORMAL, ...)
xy: window offset (x, y) of upper left corner in pixels
xySize: window size (width, height) in pixels
desktop: lpDesktop - name of desktop e.g. 'winsta0\\default'
None = inherit current desktop
'' = create new desktop if necessary
User calling login requires additional privileges:
Act as part of the operating system [not needed on Windows XP]
Increase quotas
Replace a process level token
Login string must EITHER be an administrator's account
(ordinary user can't access current desktop - see Microsoft
Q165194) OR use desktop='' to run another desktop invisibly
(may be very slow to startup & finalize).
"""
si = win32process.STARTUPINFO()
si.dwFlags = (win32con.STARTF_USESTDHANDLES ^
win32con.STARTF_USESHOWWINDOW)
if hStdin is None:
si.hStdInput = win32api.GetStdHandle(win32api.STD_INPUT_HANDLE)
else:
si.hStdInput = hStdin
if hStdout is None:
si.hStdOutput = win32api.GetStdHandle(win32api.STD_OUTPUT_HANDLE)
else:
si.hStdOutput = hStdout
if hStderr is None:
si.hStdError = win32api.GetStdHandle(win32api.STD_ERROR_HANDLE)
else:
si.hStdError = hStderr
si.wShowWindow = show
if xy is not None:
si.dwX, si.dwY = xy
si.dwFlags ^= win32con.STARTF_USEPOSITION
if xySize is not None:
si.dwXSize, si.dwYSize = xySize
si.dwFlags ^= win32con.STARTF_USESIZE
if desktop is not None:
si.lpDesktop = desktop
procArgs = (None, # appName
cmd, # commandLine
None, # processAttributes
None, # threadAttributes
1, # bInheritHandles
win32process.CREATE_NEW_CONSOLE, # dwCreationFlags
None, # newEnvironment
None, # currentDirectory
si) # startupinfo
if login is not None:
hUser = logonUser(login)
win32security.ImpersonateLoggedOnUser(hUser)
procHandles = win32process.CreateProcessAsUser(hUser, *procArgs)
win32security.RevertToSelf()
else:
procHandles = win32process.CreateProcess(*procArgs)
self.hProcess, self.hThread, self.PId, self.TId = procHandles
def wait(self, mSec=None):
"""
Wait for process to finish or for specified number of
milliseconds to elapse.
"""
if mSec is None:
mSec = win32event.INFINITE
return win32event.WaitForSingleObject(self.hProcess, mSec)
def kill(self, gracePeriod=5000):
"""
Kill process. Try for an orderly shutdown via WM_CLOSE. If
still running after gracePeriod (5 sec. default), terminate.
"""
win32gui.EnumWindows(self.__close__, 0)
if self.wait(gracePeriod) != win32event.WAIT_OBJECT_0:
win32process.TerminateProcess(self.hProcess, 0)
win32api.Sleep(100) # wait for resources to be released
def __close__(self, hwnd, dummy):
"""
EnumWindows callback - sends WM_CLOSE to any window
owned by this process.
"""
TId, PId = win32process.GetWindowThreadProcessId(hwnd)
if PId == self.PId:
win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0)
def exitCode(self):
"""
Return process exit code.
"""
return win32process.GetExitCodeProcess(self.hProcess)
def run(cmd, mSec=None, stdin=None, stdout=None, stderr=None, **kw):
"""
Run cmd as a child process and return exit code.
mSec: terminate cmd after specified number of milliseconds
stdin, stdout, stderr:
file objects for child I/O (use hStdin etc. to attach
handles instead of files); default is caller's stdin,
stdout & stderr;
kw: see Process.__init__ for more keyword options
"""
if stdin is not None:
kw['hStdin'] = msvcrt.get_osfhandle(stdin.fileno())
if stdout is not None:
kw['hStdout'] = msvcrt.get_osfhandle(stdout.fileno())
if stderr is not None:
<|fim_middle|>
child = Process(cmd, **kw)
if child.wait(mSec) != win32event.WAIT_OBJECT_0:
child.kill()
raise WindowsError, 'process timeout exceeded'
return child.exitCode()
if __name__ == '__main__':
# Pipe commands to a shell and display the output in notepad
print 'Testing winprocess.py...'
import tempfile
timeoutSeconds = 15
cmdString = """\
REM Test of winprocess.py piping commands to a shell.\r
REM This window will close in %d seconds.\r
vol\r
net user\r
_this_is_a_test_of_stderr_\r
""" % timeoutSeconds
cmd, out = tempfile.TemporaryFile(), tempfile.TemporaryFile()
cmd.write(cmdString)
cmd.seek(0)
print 'CMD.EXE exit code:', run('cmd.exe', show=0, stdin=cmd,
stdout=out, stderr=out)
cmd.close()
print 'NOTEPAD exit code:', run('notepad.exe %s' % out.file.name,
show=win32con.SW_MAXIMIZE,
mSec=timeoutSeconds*1000)
out.close()
<|fim▁end|> | kw['hStderr'] = msvcrt.get_osfhandle(stderr.fileno()) |
<|file_name|>winprocess.py<|end_file_name|><|fim▁begin|>"""
Windows Process Control
winprocess.run launches a child process and returns the exit code.
Optionally, it can:
redirect stdin, stdout & stderr to files
run the command as another user
limit the process's running time
control the process window (location, size, window state, desktop)
Works on Windows NT, 2000 & XP. Requires Mark Hammond's win32
extensions.
This code is free for any purpose, with no warranty of any kind.
-- John B. Dell'Aquila <[email protected]>
"""
import win32api, win32process, win32security
import win32event, win32con, msvcrt, win32gui
def logonUser(loginString):
"""
Login as specified user and return handle.
loginString: 'Domain\nUser\nPassword'; for local
login use . or empty string as domain
e.g. '.\nadministrator\nsecret_password'
"""
domain, user, passwd = loginString.split('\n')
return win32security.LogonUser(
user,
domain,
passwd,
win32con.LOGON32_LOGON_INTERACTIVE,
win32con.LOGON32_PROVIDER_DEFAULT
)
class Process:
"""
A Windows process.
"""
def __init__(self, cmd, login=None,
hStdin=None, hStdout=None, hStderr=None,
show=1, xy=None, xySize=None,
desktop=None):
"""
Create a Windows process.
cmd: command to run
login: run as user 'Domain\nUser\nPassword'
hStdin, hStdout, hStderr:
handles for process I/O; default is caller's stdin,
stdout & stderr
show: wShowWindow (0=SW_HIDE, 1=SW_NORMAL, ...)
xy: window offset (x, y) of upper left corner in pixels
xySize: window size (width, height) in pixels
desktop: lpDesktop - name of desktop e.g. 'winsta0\\default'
None = inherit current desktop
'' = create new desktop if necessary
User calling login requires additional privileges:
Act as part of the operating system [not needed on Windows XP]
Increase quotas
Replace a process level token
Login string must EITHER be an administrator's account
(ordinary user can't access current desktop - see Microsoft
Q165194) OR use desktop='' to run another desktop invisibly
(may be very slow to startup & finalize).
"""
si = win32process.STARTUPINFO()
si.dwFlags = (win32con.STARTF_USESTDHANDLES ^
win32con.STARTF_USESHOWWINDOW)
if hStdin is None:
si.hStdInput = win32api.GetStdHandle(win32api.STD_INPUT_HANDLE)
else:
si.hStdInput = hStdin
if hStdout is None:
si.hStdOutput = win32api.GetStdHandle(win32api.STD_OUTPUT_HANDLE)
else:
si.hStdOutput = hStdout
if hStderr is None:
si.hStdError = win32api.GetStdHandle(win32api.STD_ERROR_HANDLE)
else:
si.hStdError = hStderr
si.wShowWindow = show
if xy is not None:
si.dwX, si.dwY = xy
si.dwFlags ^= win32con.STARTF_USEPOSITION
if xySize is not None:
si.dwXSize, si.dwYSize = xySize
si.dwFlags ^= win32con.STARTF_USESIZE
if desktop is not None:
si.lpDesktop = desktop
procArgs = (None, # appName
cmd, # commandLine
None, # processAttributes
None, # threadAttributes
1, # bInheritHandles
win32process.CREATE_NEW_CONSOLE, # dwCreationFlags
None, # newEnvironment
None, # currentDirectory
si) # startupinfo
if login is not None:
hUser = logonUser(login)
win32security.ImpersonateLoggedOnUser(hUser)
procHandles = win32process.CreateProcessAsUser(hUser, *procArgs)
win32security.RevertToSelf()
else:
procHandles = win32process.CreateProcess(*procArgs)
self.hProcess, self.hThread, self.PId, self.TId = procHandles
def wait(self, mSec=None):
"""
Wait for process to finish or for specified number of
milliseconds to elapse.
"""
if mSec is None:
mSec = win32event.INFINITE
return win32event.WaitForSingleObject(self.hProcess, mSec)
def kill(self, gracePeriod=5000):
"""
Kill process. Try for an orderly shutdown via WM_CLOSE. If
still running after gracePeriod (5 sec. default), terminate.
"""
win32gui.EnumWindows(self.__close__, 0)
if self.wait(gracePeriod) != win32event.WAIT_OBJECT_0:
win32process.TerminateProcess(self.hProcess, 0)
win32api.Sleep(100) # wait for resources to be released
def __close__(self, hwnd, dummy):
"""
EnumWindows callback - sends WM_CLOSE to any window
owned by this process.
"""
TId, PId = win32process.GetWindowThreadProcessId(hwnd)
if PId == self.PId:
win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0)
def exitCode(self):
"""
Return process exit code.
"""
return win32process.GetExitCodeProcess(self.hProcess)
def run(cmd, mSec=None, stdin=None, stdout=None, stderr=None, **kw):
"""
Run cmd as a child process and return exit code.
mSec: terminate cmd after specified number of milliseconds
stdin, stdout, stderr:
file objects for child I/O (use hStdin etc. to attach
handles instead of files); default is caller's stdin,
stdout & stderr;
kw: see Process.__init__ for more keyword options
"""
if stdin is not None:
kw['hStdin'] = msvcrt.get_osfhandle(stdin.fileno())
if stdout is not None:
kw['hStdout'] = msvcrt.get_osfhandle(stdout.fileno())
if stderr is not None:
kw['hStderr'] = msvcrt.get_osfhandle(stderr.fileno())
child = Process(cmd, **kw)
if child.wait(mSec) != win32event.WAIT_OBJECT_0:
<|fim_middle|>
return child.exitCode()
if __name__ == '__main__':
# Pipe commands to a shell and display the output in notepad
print 'Testing winprocess.py...'
import tempfile
timeoutSeconds = 15
cmdString = """\
REM Test of winprocess.py piping commands to a shell.\r
REM This window will close in %d seconds.\r
vol\r
net user\r
_this_is_a_test_of_stderr_\r
""" % timeoutSeconds
cmd, out = tempfile.TemporaryFile(), tempfile.TemporaryFile()
cmd.write(cmdString)
cmd.seek(0)
print 'CMD.EXE exit code:', run('cmd.exe', show=0, stdin=cmd,
stdout=out, stderr=out)
cmd.close()
print 'NOTEPAD exit code:', run('notepad.exe %s' % out.file.name,
show=win32con.SW_MAXIMIZE,
mSec=timeoutSeconds*1000)
out.close()
<|fim▁end|> | child.kill()
raise WindowsError, 'process timeout exceeded' |
<|file_name|>winprocess.py<|end_file_name|><|fim▁begin|>"""
Windows Process Control
winprocess.run launches a child process and returns the exit code.
Optionally, it can:
redirect stdin, stdout & stderr to files
run the command as another user
limit the process's running time
control the process window (location, size, window state, desktop)
Works on Windows NT, 2000 & XP. Requires Mark Hammond's win32
extensions.
This code is free for any purpose, with no warranty of any kind.
-- John B. Dell'Aquila <[email protected]>
"""
import win32api, win32process, win32security
import win32event, win32con, msvcrt, win32gui
def logonUser(loginString):
"""
Login as specified user and return handle.
loginString: 'Domain\nUser\nPassword'; for local
login use . or empty string as domain
e.g. '.\nadministrator\nsecret_password'
"""
domain, user, passwd = loginString.split('\n')
return win32security.LogonUser(
user,
domain,
passwd,
win32con.LOGON32_LOGON_INTERACTIVE,
win32con.LOGON32_PROVIDER_DEFAULT
)
class Process:
"""
A Windows process.
"""
def __init__(self, cmd, login=None,
hStdin=None, hStdout=None, hStderr=None,
show=1, xy=None, xySize=None,
desktop=None):
"""
Create a Windows process.
cmd: command to run
login: run as user 'Domain\nUser\nPassword'
hStdin, hStdout, hStderr:
handles for process I/O; default is caller's stdin,
stdout & stderr
show: wShowWindow (0=SW_HIDE, 1=SW_NORMAL, ...)
xy: window offset (x, y) of upper left corner in pixels
xySize: window size (width, height) in pixels
desktop: lpDesktop - name of desktop e.g. 'winsta0\\default'
None = inherit current desktop
'' = create new desktop if necessary
User calling login requires additional privileges:
Act as part of the operating system [not needed on Windows XP]
Increase quotas
Replace a process level token
Login string must EITHER be an administrator's account
(ordinary user can't access current desktop - see Microsoft
Q165194) OR use desktop='' to run another desktop invisibly
(may be very slow to startup & finalize).
"""
si = win32process.STARTUPINFO()
si.dwFlags = (win32con.STARTF_USESTDHANDLES ^
win32con.STARTF_USESHOWWINDOW)
if hStdin is None:
si.hStdInput = win32api.GetStdHandle(win32api.STD_INPUT_HANDLE)
else:
si.hStdInput = hStdin
if hStdout is None:
si.hStdOutput = win32api.GetStdHandle(win32api.STD_OUTPUT_HANDLE)
else:
si.hStdOutput = hStdout
if hStderr is None:
si.hStdError = win32api.GetStdHandle(win32api.STD_ERROR_HANDLE)
else:
si.hStdError = hStderr
si.wShowWindow = show
if xy is not None:
si.dwX, si.dwY = xy
si.dwFlags ^= win32con.STARTF_USEPOSITION
if xySize is not None:
si.dwXSize, si.dwYSize = xySize
si.dwFlags ^= win32con.STARTF_USESIZE
if desktop is not None:
si.lpDesktop = desktop
procArgs = (None, # appName
cmd, # commandLine
None, # processAttributes
None, # threadAttributes
1, # bInheritHandles
win32process.CREATE_NEW_CONSOLE, # dwCreationFlags
None, # newEnvironment
None, # currentDirectory
si) # startupinfo
if login is not None:
hUser = logonUser(login)
win32security.ImpersonateLoggedOnUser(hUser)
procHandles = win32process.CreateProcessAsUser(hUser, *procArgs)
win32security.RevertToSelf()
else:
procHandles = win32process.CreateProcess(*procArgs)
self.hProcess, self.hThread, self.PId, self.TId = procHandles
def wait(self, mSec=None):
"""
Wait for process to finish or for specified number of
milliseconds to elapse.
"""
if mSec is None:
mSec = win32event.INFINITE
return win32event.WaitForSingleObject(self.hProcess, mSec)
def kill(self, gracePeriod=5000):
"""
Kill process. Try for an orderly shutdown via WM_CLOSE. If
still running after gracePeriod (5 sec. default), terminate.
"""
win32gui.EnumWindows(self.__close__, 0)
if self.wait(gracePeriod) != win32event.WAIT_OBJECT_0:
win32process.TerminateProcess(self.hProcess, 0)
win32api.Sleep(100) # wait for resources to be released
def __close__(self, hwnd, dummy):
"""
EnumWindows callback - sends WM_CLOSE to any window
owned by this process.
"""
TId, PId = win32process.GetWindowThreadProcessId(hwnd)
if PId == self.PId:
win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0)
def exitCode(self):
"""
Return process exit code.
"""
return win32process.GetExitCodeProcess(self.hProcess)
def run(cmd, mSec=None, stdin=None, stdout=None, stderr=None, **kw):
"""
Run cmd as a child process and return exit code.
mSec: terminate cmd after specified number of milliseconds
stdin, stdout, stderr:
file objects for child I/O (use hStdin etc. to attach
handles instead of files); default is caller's stdin,
stdout & stderr;
kw: see Process.__init__ for more keyword options
"""
if stdin is not None:
kw['hStdin'] = msvcrt.get_osfhandle(stdin.fileno())
if stdout is not None:
kw['hStdout'] = msvcrt.get_osfhandle(stdout.fileno())
if stderr is not None:
kw['hStderr'] = msvcrt.get_osfhandle(stderr.fileno())
child = Process(cmd, **kw)
if child.wait(mSec) != win32event.WAIT_OBJECT_0:
child.kill()
raise WindowsError, 'process timeout exceeded'
return child.exitCode()
if __name__ == '__main__':
# Pipe commands to a shell and display the output in notepad
<|fim_middle|>
<|fim▁end|> | print 'Testing winprocess.py...'
import tempfile
timeoutSeconds = 15
cmdString = """\
REM Test of winprocess.py piping commands to a shell.\r
REM This window will close in %d seconds.\r
vol\r
net user\r
_this_is_a_test_of_stderr_\r
""" % timeoutSeconds
cmd, out = tempfile.TemporaryFile(), tempfile.TemporaryFile()
cmd.write(cmdString)
cmd.seek(0)
print 'CMD.EXE exit code:', run('cmd.exe', show=0, stdin=cmd,
stdout=out, stderr=out)
cmd.close()
print 'NOTEPAD exit code:', run('notepad.exe %s' % out.file.name,
show=win32con.SW_MAXIMIZE,
mSec=timeoutSeconds*1000)
out.close() |
<|file_name|>winprocess.py<|end_file_name|><|fim▁begin|>"""
Windows Process Control
winprocess.run launches a child process and returns the exit code.
Optionally, it can:
redirect stdin, stdout & stderr to files
run the command as another user
limit the process's running time
control the process window (location, size, window state, desktop)
Works on Windows NT, 2000 & XP. Requires Mark Hammond's win32
extensions.
This code is free for any purpose, with no warranty of any kind.
-- John B. Dell'Aquila <[email protected]>
"""
import win32api, win32process, win32security
import win32event, win32con, msvcrt, win32gui
def <|fim_middle|>(loginString):
"""
Login as specified user and return handle.
loginString: 'Domain\nUser\nPassword'; for local
login use . or empty string as domain
e.g. '.\nadministrator\nsecret_password'
"""
domain, user, passwd = loginString.split('\n')
return win32security.LogonUser(
user,
domain,
passwd,
win32con.LOGON32_LOGON_INTERACTIVE,
win32con.LOGON32_PROVIDER_DEFAULT
)
class Process:
"""
A Windows process.
"""
def __init__(self, cmd, login=None,
hStdin=None, hStdout=None, hStderr=None,
show=1, xy=None, xySize=None,
desktop=None):
"""
Create a Windows process.
cmd: command to run
login: run as user 'Domain\nUser\nPassword'
hStdin, hStdout, hStderr:
handles for process I/O; default is caller's stdin,
stdout & stderr
show: wShowWindow (0=SW_HIDE, 1=SW_NORMAL, ...)
xy: window offset (x, y) of upper left corner in pixels
xySize: window size (width, height) in pixels
desktop: lpDesktop - name of desktop e.g. 'winsta0\\default'
None = inherit current desktop
'' = create new desktop if necessary
User calling login requires additional privileges:
Act as part of the operating system [not needed on Windows XP]
Increase quotas
Replace a process level token
Login string must EITHER be an administrator's account
(ordinary user can't access current desktop - see Microsoft
Q165194) OR use desktop='' to run another desktop invisibly
(may be very slow to startup & finalize).
"""
si = win32process.STARTUPINFO()
si.dwFlags = (win32con.STARTF_USESTDHANDLES ^
win32con.STARTF_USESHOWWINDOW)
if hStdin is None:
si.hStdInput = win32api.GetStdHandle(win32api.STD_INPUT_HANDLE)
else:
si.hStdInput = hStdin
if hStdout is None:
si.hStdOutput = win32api.GetStdHandle(win32api.STD_OUTPUT_HANDLE)
else:
si.hStdOutput = hStdout
if hStderr is None:
si.hStdError = win32api.GetStdHandle(win32api.STD_ERROR_HANDLE)
else:
si.hStdError = hStderr
si.wShowWindow = show
if xy is not None:
si.dwX, si.dwY = xy
si.dwFlags ^= win32con.STARTF_USEPOSITION
if xySize is not None:
si.dwXSize, si.dwYSize = xySize
si.dwFlags ^= win32con.STARTF_USESIZE
if desktop is not None:
si.lpDesktop = desktop
procArgs = (None, # appName
cmd, # commandLine
None, # processAttributes
None, # threadAttributes
1, # bInheritHandles
win32process.CREATE_NEW_CONSOLE, # dwCreationFlags
None, # newEnvironment
None, # currentDirectory
si) # startupinfo
if login is not None:
hUser = logonUser(login)
win32security.ImpersonateLoggedOnUser(hUser)
procHandles = win32process.CreateProcessAsUser(hUser, *procArgs)
win32security.RevertToSelf()
else:
procHandles = win32process.CreateProcess(*procArgs)
self.hProcess, self.hThread, self.PId, self.TId = procHandles
def wait(self, mSec=None):
"""
Wait for process to finish or for specified number of
milliseconds to elapse.
"""
if mSec is None:
mSec = win32event.INFINITE
return win32event.WaitForSingleObject(self.hProcess, mSec)
def kill(self, gracePeriod=5000):
"""
Kill process. Try for an orderly shutdown via WM_CLOSE. If
still running after gracePeriod (5 sec. default), terminate.
"""
win32gui.EnumWindows(self.__close__, 0)
if self.wait(gracePeriod) != win32event.WAIT_OBJECT_0:
win32process.TerminateProcess(self.hProcess, 0)
win32api.Sleep(100) # wait for resources to be released
def __close__(self, hwnd, dummy):
"""
EnumWindows callback - sends WM_CLOSE to any window
owned by this process.
"""
TId, PId = win32process.GetWindowThreadProcessId(hwnd)
if PId == self.PId:
win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0)
def exitCode(self):
"""
Return process exit code.
"""
return win32process.GetExitCodeProcess(self.hProcess)
def run(cmd, mSec=None, stdin=None, stdout=None, stderr=None, **kw):
"""
Run cmd as a child process and return exit code.
mSec: terminate cmd after specified number of milliseconds
stdin, stdout, stderr:
file objects for child I/O (use hStdin etc. to attach
handles instead of files); default is caller's stdin,
stdout & stderr;
kw: see Process.__init__ for more keyword options
"""
if stdin is not None:
kw['hStdin'] = msvcrt.get_osfhandle(stdin.fileno())
if stdout is not None:
kw['hStdout'] = msvcrt.get_osfhandle(stdout.fileno())
if stderr is not None:
kw['hStderr'] = msvcrt.get_osfhandle(stderr.fileno())
child = Process(cmd, **kw)
if child.wait(mSec) != win32event.WAIT_OBJECT_0:
child.kill()
raise WindowsError, 'process timeout exceeded'
return child.exitCode()
if __name__ == '__main__':
# Pipe commands to a shell and display the output in notepad
print 'Testing winprocess.py...'
import tempfile
timeoutSeconds = 15
cmdString = """\
REM Test of winprocess.py piping commands to a shell.\r
REM This window will close in %d seconds.\r
vol\r
net user\r
_this_is_a_test_of_stderr_\r
""" % timeoutSeconds
cmd, out = tempfile.TemporaryFile(), tempfile.TemporaryFile()
cmd.write(cmdString)
cmd.seek(0)
print 'CMD.EXE exit code:', run('cmd.exe', show=0, stdin=cmd,
stdout=out, stderr=out)
cmd.close()
print 'NOTEPAD exit code:', run('notepad.exe %s' % out.file.name,
show=win32con.SW_MAXIMIZE,
mSec=timeoutSeconds*1000)
out.close()
<|fim▁end|> | logonUser |
<|file_name|>winprocess.py<|end_file_name|><|fim▁begin|>"""
Windows Process Control
winprocess.run launches a child process and returns the exit code.
Optionally, it can:
redirect stdin, stdout & stderr to files
run the command as another user
limit the process's running time
control the process window (location, size, window state, desktop)
Works on Windows NT, 2000 & XP. Requires Mark Hammond's win32
extensions.
This code is free for any purpose, with no warranty of any kind.
-- John B. Dell'Aquila <[email protected]>
"""
import win32api, win32process, win32security
import win32event, win32con, msvcrt, win32gui
def logonUser(loginString):
"""
Login as specified user and return handle.
loginString: 'Domain\nUser\nPassword'; for local
login use . or empty string as domain
e.g. '.\nadministrator\nsecret_password'
"""
domain, user, passwd = loginString.split('\n')
return win32security.LogonUser(
user,
domain,
passwd,
win32con.LOGON32_LOGON_INTERACTIVE,
win32con.LOGON32_PROVIDER_DEFAULT
)
class Process:
"""
A Windows process.
"""
def <|fim_middle|>(self, cmd, login=None,
hStdin=None, hStdout=None, hStderr=None,
show=1, xy=None, xySize=None,
desktop=None):
"""
Create a Windows process.
cmd: command to run
login: run as user 'Domain\nUser\nPassword'
hStdin, hStdout, hStderr:
handles for process I/O; default is caller's stdin,
stdout & stderr
show: wShowWindow (0=SW_HIDE, 1=SW_NORMAL, ...)
xy: window offset (x, y) of upper left corner in pixels
xySize: window size (width, height) in pixels
desktop: lpDesktop - name of desktop e.g. 'winsta0\\default'
None = inherit current desktop
'' = create new desktop if necessary
User calling login requires additional privileges:
Act as part of the operating system [not needed on Windows XP]
Increase quotas
Replace a process level token
Login string must EITHER be an administrator's account
(ordinary user can't access current desktop - see Microsoft
Q165194) OR use desktop='' to run another desktop invisibly
(may be very slow to startup & finalize).
"""
si = win32process.STARTUPINFO()
si.dwFlags = (win32con.STARTF_USESTDHANDLES ^
win32con.STARTF_USESHOWWINDOW)
if hStdin is None:
si.hStdInput = win32api.GetStdHandle(win32api.STD_INPUT_HANDLE)
else:
si.hStdInput = hStdin
if hStdout is None:
si.hStdOutput = win32api.GetStdHandle(win32api.STD_OUTPUT_HANDLE)
else:
si.hStdOutput = hStdout
if hStderr is None:
si.hStdError = win32api.GetStdHandle(win32api.STD_ERROR_HANDLE)
else:
si.hStdError = hStderr
si.wShowWindow = show
if xy is not None:
si.dwX, si.dwY = xy
si.dwFlags ^= win32con.STARTF_USEPOSITION
if xySize is not None:
si.dwXSize, si.dwYSize = xySize
si.dwFlags ^= win32con.STARTF_USESIZE
if desktop is not None:
si.lpDesktop = desktop
procArgs = (None, # appName
cmd, # commandLine
None, # processAttributes
None, # threadAttributes
1, # bInheritHandles
win32process.CREATE_NEW_CONSOLE, # dwCreationFlags
None, # newEnvironment
None, # currentDirectory
si) # startupinfo
if login is not None:
hUser = logonUser(login)
win32security.ImpersonateLoggedOnUser(hUser)
procHandles = win32process.CreateProcessAsUser(hUser, *procArgs)
win32security.RevertToSelf()
else:
procHandles = win32process.CreateProcess(*procArgs)
self.hProcess, self.hThread, self.PId, self.TId = procHandles
def wait(self, mSec=None):
"""
Wait for process to finish or for specified number of
milliseconds to elapse.
"""
if mSec is None:
mSec = win32event.INFINITE
return win32event.WaitForSingleObject(self.hProcess, mSec)
def kill(self, gracePeriod=5000):
"""
Kill process. Try for an orderly shutdown via WM_CLOSE. If
still running after gracePeriod (5 sec. default), terminate.
"""
win32gui.EnumWindows(self.__close__, 0)
if self.wait(gracePeriod) != win32event.WAIT_OBJECT_0:
win32process.TerminateProcess(self.hProcess, 0)
win32api.Sleep(100) # wait for resources to be released
def __close__(self, hwnd, dummy):
"""
EnumWindows callback - sends WM_CLOSE to any window
owned by this process.
"""
TId, PId = win32process.GetWindowThreadProcessId(hwnd)
if PId == self.PId:
win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0)
def exitCode(self):
"""
Return process exit code.
"""
return win32process.GetExitCodeProcess(self.hProcess)
def run(cmd, mSec=None, stdin=None, stdout=None, stderr=None, **kw):
"""
Run cmd as a child process and return exit code.
mSec: terminate cmd after specified number of milliseconds
stdin, stdout, stderr:
file objects for child I/O (use hStdin etc. to attach
handles instead of files); default is caller's stdin,
stdout & stderr;
kw: see Process.__init__ for more keyword options
"""
if stdin is not None:
kw['hStdin'] = msvcrt.get_osfhandle(stdin.fileno())
if stdout is not None:
kw['hStdout'] = msvcrt.get_osfhandle(stdout.fileno())
if stderr is not None:
kw['hStderr'] = msvcrt.get_osfhandle(stderr.fileno())
child = Process(cmd, **kw)
if child.wait(mSec) != win32event.WAIT_OBJECT_0:
child.kill()
raise WindowsError, 'process timeout exceeded'
return child.exitCode()
if __name__ == '__main__':
# Pipe commands to a shell and display the output in notepad
print 'Testing winprocess.py...'
import tempfile
timeoutSeconds = 15
cmdString = """\
REM Test of winprocess.py piping commands to a shell.\r
REM This window will close in %d seconds.\r
vol\r
net user\r
_this_is_a_test_of_stderr_\r
""" % timeoutSeconds
cmd, out = tempfile.TemporaryFile(), tempfile.TemporaryFile()
cmd.write(cmdString)
cmd.seek(0)
print 'CMD.EXE exit code:', run('cmd.exe', show=0, stdin=cmd,
stdout=out, stderr=out)
cmd.close()
print 'NOTEPAD exit code:', run('notepad.exe %s' % out.file.name,
show=win32con.SW_MAXIMIZE,
mSec=timeoutSeconds*1000)
out.close()
<|fim▁end|> | __init__ |
Subsets and Splits