本文整理汇总了Python中executor.Executor类的典型用法代码示例。如果您正苦于以下问题:Python Executor类的具体用法?Python Executor怎么用?Python Executor使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Executor类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: REPL
class REPL(Cmd):
prompt = 'repl:>> '
def __init__(self):
Cmd.__init__(self)
self.ex = Executor()
self.trans = translator.Translator()
def default(self, line):
try:
y = yaml.load(line)
print 'yaml:', y
js = self.trans.translate(y)
print 'generated js:', js
print self.ex.execute(js)
except Exception as e:
print e
def do_EOF(self, line):
return True
def do_quit(self, line):
return True
def do_reload(self, line):
reload(translator)
self.trans = translator.Translator()
return False
示例2: _process_event
def _process_event(self, event):
global config
if event:
# This still needs some work
# dependencies = self._check_for_dependencies(config, event)
dependencies = []
self.job_count += 1
job_id = "%s:%d" % (self.name, self.job_count)
try:
# Launch test runs
tests = []
for test in config['tests']:
testexec = Executor(test, event, dependencies)
tests.append(testexec)
testexec.start()
logging.info('Started %s test execution...',
test['test-name'])
# Wait for all executions to finish
for test in tests:
test.join()
logging.info('All tests completed')
# Report the results
self._publish_results_to_gerrit(
config, tests, job_id)
# Throttle things a little bit
time.sleep(5)
except Exception:
logging.exception('Error in event processing!')
示例3: LiquipyDatabase
class LiquipyDatabase(object):
"""
Main interface for Liquipy
"""
def __init__(self, host=DEFAULT['host'],
database=DEFAULT['database'],
username=DEFAULT['username'],
password=DEFAULT['password'],
tempDir=DEFAULT['tempDir']):
self.liquibaseExecutor = LiquibaseExecutor(host, database, username, password)
self.tempDir = tempDir
self.outputXmlChangeLogFilePath = self.tempDir + "/liquipy_changelog.xml"
def initialize(self, yamlPath):
rawYaml = open(yamlPath, 'r').read()
try:
changes = yaml.load(rawYaml)
except yaml.scanner.ScannerError as e:
msg = "Error parsing input YAML file '%s':\n%s" % (yamlPath, e)
raise Exception(msg)
changeSetWriter = ChangeSetWriter(self.outputXmlChangeLogFilePath)
changeSetWriter.write(changes)
def update(self):
self.liquibaseExecutor.run(self.outputXmlChangeLogFilePath, 'update')
示例4: show_pattern_and_template
def show_pattern_and_template(dna):
from executor import Executor
e = Executor(dna)
e.explicit_rna_items = True
pattern = e.pattern()
pattern.append('EoP')
template = e.template()
template.append('EoT')
e.item_starts.append(e.parser.index)
s1 = []
s2 = []
for item, begin, end in zip(
pattern+template,
e.item_starts,
e.item_starts[1:]):
e1 = ''.join(e.dna[begin:end])
e2 = str(item)
if len(e1) > len(e2):
e2 += ' '*(len(e1)-len(e2))
else:
e1 += ' '*(len(e2)-len(e1))
s1.append(e1)
s2.append(e2)
print ' '.join(s1)
print ' '.join(s2)
示例5: kill_device
def kill_device(device):
cmd = "ps xww | grep Simulator.app | grep -s {0} | grep -v grep | awk '{{print $1}}'".format(device.uuid)
output = Executor.execute(cmd)
if output == '':
return
pid = int(output)
if pid > 0:
Executor.execute('kill {0}'.format(pid))
示例6: Hostapd
class Hostapd(object):
""" Wrapper class for UCI (OpenWRT) commands """
executor = None
devicename = None
def __init__(self, config = "/etc/hostapd/hostapd.conf", wifi_restart_command, executor=None):
if executor == None:
self.executor = Executor()
else:
self.executor = executor
self.config = config
self.restart_command = wifi_restart_command
def get_wifi_interface(self):
"Return the wifi interface name (e.g. 'wlan0')"
ret = self.executor.execute_cmd(['grep', '^interface', self.config, '|', 'cut','-f2','-d"="'])
if ret is None:
print 'No WiFi device name found.'
return ret
def get_bridge_interface(self):
"Return the bridge interface name (e.g. 'br0')"
ret = self.executor.execute_cmd(['grep', '^bridge', self.config, '|', 'cut','-f2','-d"="'])
if ret is None:
print 'No bridge device name found.'
return ret
def get_wifi_mode(self):
"Get operation mode (e.g. n)"
ret = self.executor.execute_cmd(['grep', '^hw_mode', self.config, '|', 'cut','-f2','-d"="'])
if ret is None:
print 'No mode found in config.'
return ret
def set_channel(self, channel):
"Sets the wifi channel. Requires commit and restart of WiFi for changes to take effect"
self.executor.execute_cmd(['sudo','cat',self.config,'|','sed','-e',"s/channel=[0-9][0-9]*/channel=%d/g" % channel, '>', '/tmp/tmp_hostapd.conf'])
self.executor.execute_cmd(['sudo','mv','/tmp/tmp_hostapd.conf',self.config])
def restart():
"Restart hostapd"
self.executor.execute_cmd(wifi_restart_command)
def get_wifi_ssid(self):
"Return the wifi ssid (e.g. for 'node1-wifi')"
ret = self.executor.execute_cmd(['grep', '^ssid', self.config, '|', 'cut','-f2','-d"="'])
if ret is None:
print 'No SSID found in config.'
return ret
示例7: LiquipyDatabase
class LiquipyDatabase(object):
"""
Main interface for Liquipy
"""
def __init__(
self,
host=DEFAULT["host"],
database=DEFAULT["database"],
username=DEFAULT["username"],
password=DEFAULT["password"],
tempDir=DEFAULT["tempDir"],
):
self.liquibaseExecutor = LiquibaseExecutor(host, database, username, password)
self.tempDir = tempDir
self.outputXmlChangeLogFilePath = self.tempDir + "/liquipy_changelog.xml"
def initialize(self, yamlPath):
self.changes = self.inputYamlToChangeSets(yamlPath)
changeSetWriter = ChangeSetWriter(self.outputXmlChangeLogFilePath)
changeSetWriter.write(self.changes)
def inputYamlToChangeSets(self, yamlPath):
rawYaml = open(yamlPath, "r").read()
try:
changes = yaml.load(rawYaml)
except yaml.scanner.ScannerError as e:
msg = "Error parsing input YAML file '%s':\n%s" % (yamlPath, e)
raise Exception(msg)
if "include" in changes.keys():
relativeTargetDir = changes["include"]["directory"]
currentDir = join(split(yamlPath)[:-1])[0]
targetDir = join(currentDir, relativeTargetDir)
try:
dirFiles = listdir(targetDir)
except Exception:
raise Exception('Included directory "' + targetDir + '" does not exist')
migrationFiles = [join(targetDir, f) for f in dirFiles if f.endswith(".yml")]
for includedMigration in migrationFiles:
includeChanges = self.inputYamlToChangeSets(includedMigration)
changes.update(includeChanges)
del changes["include"]
return changes
def update(self):
print "Running all migrations..."
self.liquibaseExecutor.run(self.outputXmlChangeLogFilePath, "update")
def rollback(self, tagName):
print "Rolling back to %s..." % (tagName,)
self.liquibaseExecutor.run(self.outputXmlChangeLogFilePath, "rollback", tagName)
def getTags(self):
return [
{"tag": self.changes[c]["tag"], "changeSet": c} for c in self.changes.keys() if "tag" in self.changes[c]
]
示例8: delete
def delete(self):
kw = dict((self._basic_fields[i], self.values[i]) for i in self._pk)
kw['multi'] = None
kw['alias'] = self.__alias__
kw['uin'] = self._uin
w = ' AND '.join('%s = :%s' % (self._basic_fields[i], i) for i in self._pk)
if w:
w = 'WHERE ' + w
Executor.save('DELETE FROM %s %s' % (self.__table__, w), **kw)
示例9: save
def save(self, **kw):
isnew = kw.pop('isnew', any(self.values[i] is None for i in self._pk))
if self._dirty or isnew:
# set default volumes
for i in self._basic_fields.keys():
if self.values[i] is None:
x = self._fields[i]._default
if isinstance(x, (FunctionType, MethodType, BuiltinFunctionType, BuiltinMethodType,)):
x = x()
elif isinstance(x, Sequence):
# print 'W1', x
x = x()
# print 'W2', x
self.__setattr__(i, x)
kw = {'alias': self.__alias__}
if isnew:
fields = []
for i in self._dirty:
k = self._basic_fields[i]
kw[k] = self.values[i]
fields.append(k)
sql = 'INSERT INTO %s (%s) VALUES (%s)' % (self.__table__,
','.join(fields),
','.join(' :%s' % i for i in fields))
else:
sets = []
whr = []
for i in self._dirty:
k = self._basic_fields[i]
kw[k] = self.values[i]
sets.append('%s = :%s' % (k, k))
for pk in self._pk:
k = self._basic_fields[pk]
kw[k] = self.old_values[pk]
whr.append('%s = :%s' % (k, k))
sql = 'UPDATE %s SET %s WHERE %s' % (self.__table__,
', '.join(sets),
' AND '.join(whr))
self._dirty = []
kw['uin'] = self._uin
Executor.save(sql, **kw)
示例10: main
def main():
current_os = sys.platform
os_commands = {'linux': 'xdg-open', 'win32': 'start', 'darwin': 'open'}
script_abs_path = os.path.dirname(os.path.abspath(__file__))
script_parent_dir = script_abs_path.rsplit(os.sep, 1)[0]
sys.path.append(script_parent_dir)
# Check if settings directory exists and create it if it doesn't
settings_dir = '{}{}settings'.format(script_abs_path, os.sep)
if not os.path.exists(settings_dir):
Executor.execute(["mkdir", settings_dir])
# Check if sync_list file exists and create it if it doesn't
sync_list_path = '{}{}sync_list.txt'.format(settings_dir, os.sep)
if not os.path.exists(sync_list_path):
Executor.execute(["touch", sync_list_path])
# Get needed command to open default text editor depending on the OS
command = None
if 'linux' in current_os:
command = os_commands['linux']
elif 'win32' in current_os:
command = os_commands['win']
elif 'darwin' in current_os:
command = os_commands['darwin']
error_message = \
"""ERROR: An error occured while trying to open
"{}" for writing.
REASON: One possible reason is that your
operating system is not supported.
Your current operating system: {}
Supported operating systems: {}
If your operating system is not in the list or
it is but you still see this error
please give a feedback to support the development
of this app and you to be able to use it.
SOLUTION: For now you can edit the sync list manually
as you open it with some text editor."""\
.format(sync_list_path, current_os, ', '.join(os_commands.keys()))
if command is None or not Executor.execute([command, sync_list_path]):
print(error_message)
示例11: __call__
def __call__(self, parent):
if isinstance(self._cls, basestring):
self._cls = Executor.classes[self._cls]
# codtition
if self._condition:
c1, c2 = [i.strip() for i in self._condition.split('=')]
if c2.startswith(parent.__class__.__name__ + '.'):
c1, c2 = c2, c1
c1a, c1b = c1.split('.')
c2a, c2b = c2.split('.')
if parent.__class__.__name__ <> c1a or self._cls.__name__ <> c2a:
raise ReferenceException('Invalid condition "%s" by classes "%s" and "%s"' % (self._condition, c1, c2))
return self._cls._read(self._multi, **{c2b:parent.values[c1b]})
# if function of SQL generating
elif self._generator:
if isinstance(self._generator, basestring):
self._generator = parent.__class__.__dict__[self._generator]
sql, kw = self._generator(parent)
# None-классы т.е. SQL-функции
if self._cls is None:
return Executor.exec_sql(sql, multi=False, **kw).data[0]
# Внешние классы
else:
return self._cls._read(self._multi, sql=sql, **kw)
示例12: __init__
def __init__(self, config = "/etc/hostapd/hostapd.conf", wifi_restart_command, executor=None):
if executor == None:
self.executor = Executor()
else:
self.executor = executor
self.config = config
self.restart_command = wifi_restart_command
示例13: __init__
def __init__(self, host=DEFAULT['host'],
database=DEFAULT['database'],
username=DEFAULT['username'],
password=DEFAULT['password'],
tempDir=DEFAULT['tempDir']):
self.liquibaseExecutor = LiquibaseExecutor(host, database, username, password)
self.tempDir = tempDir
self.outputXmlChangeLogFilePath = self.tempDir + "/liquipy_changelog.xml"
示例14: __init__
def __init__(self, limb, hover_distance = 0.15, verbose=True):
self._limb_name = limb # string
self._hover_distance = hover_distance # in meters
self._verbose = verbose # bool
self._executor = Executor(limb, verbose)
trajsvc = "baxter_adapt/imitation_server"
rospy.wait_for_service(trajsvc, 5.0)
self._trajsvc = rospy.ServiceProxy(trajsvc, Imitation)
示例15: list_runtimes
def list_runtimes(self):
output = Executor.execute(CMD.format('runtimes'))
runtime_list = json.loads(output)['runtimes']
return [RunTime(runtime['availability'],
runtime['buildversion'],
runtime['identifier'],
runtime['name'],
runtime['version']) for runtime in runtime_list]