本文整理汇总了Python中Command.Command类的典型用法代码示例。如果您正苦于以下问题:Python Command类的具体用法?Python Command怎么用?Python Command使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Command类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: insert_command_at
def insert_command_at(self, idx, command):
if command is None:
return
if isinstance(command, str):
if len(command.strip()) == 0:
raise TypeError('Passin command type is not corrent.')
command = Command(command)
self._command_order.insert(idx, command.__hash__())
self._commands[command.__hash__()] = command
elif isinstance(command, Command):
self._command_order.insert(idx, command.__hash__())
self._commands[command.__hash__()] = command
elif isinstance(command, list):
for cmd in command:
if isinstance(cmd, str):
cmd = Command(cmd)
self._command_order.insert(idx, cmd.__hash__())
self._commands[cmd.__hash__()] = cmd
elif isinstance(cmd, Command):
self._command_order.insert(idx, cmd.__hash__())
self._commands[cmd.__hash__()] = cmd
idx += 1
else:
raise TypeError('Passin command type is not corrent.')
示例2: sendCommand
def sendCommand(f):
print '--------- Datalogger Simulator -----------'
while len(sensorReceiver) > 0:
print 'Ingrese uno de los siguientes comandos:'
for key,val in sorted(command.items()):
print " "*5,key, ":", val
commandInput = raw_input('>>')
if command.has_key(commandInput):
print 'Ingrese un sensor destinatario'
for key,val in sorted(sensorReceiver.items()):
print " "*5,key, ":", val
sensorInput = raw_input('>>')
if sensorReceiver.has_key(sensorInput):
if commandInput == '1':
frequency = 0
elif commandInput == '2':
print 'Ingrese una valor de frecuencia'
frequency = raw_input('>>')
else:
frequency = 0
comando = Command(sensorReceiver[sensorInput],'client03' , 5, 100, ' ',command[commandInput], frequency)
com.send(comando)
f.write(comando.getReceiver().center(15)+ comando.getCommand().center(10) +str(comando.getValue()).center(10)
+'-'.center(10)+'-'.center(10)+ time.strftime("%H:%M:%S").center(10)+'\n')
if commandInput == '3':
del sensorReceiver[sensorInput];
else:
print 'el sensor no existe\n'
else:
print 'comando erroneo\n'
exit(0)
示例3: GameObject
class GameObject():
validObjects = ['beacon', 'tower', 'default', 'drone', 'asteroid', 'mine', 'scrap', 'worker', 'fighter'] #Definition list of all possible object type strings
def __init__(self, loc, objectType, player):
#Static attributes:
self.loc = loc
if(objectType in self.validObjects):
self.objectType = objectType
else:
self.objectType = 'default'
self.ID = None
self.player = player
self.mass = {'beacon':1000, 'tower':100, 'default':10, 'drone':10, 'asteroid':5, 'mine':1, 'scrap':1, 'worker':10, 'fighter':15}[self.objectType] #Get mass from dictionary according to the object type
#Dynamic attributes:
self.velocity = [0, 0] #Velocity vector. For example: [1, 0] refers to positive x direction at 1 unit per second
self.acceleration = [0, 0]
self.current_cmd = Command('drift') #Initialize GameObjec to drift based on initial acceleration and velocity when created
self.angle = 0
#Variable convention:
#Player: a string representing the player name the object belongs to. Same for every object the player owns
#ID: A unique ID that is dynamically assigned for each gameObject on the map. In the form player,objectType,number
def update(self): #Each game object must be updated every tick
self.current_cmd.runCmd(self)
def getDict(self):
obj_dict = self.__dict__.copy()
del obj_dict['current_cmd']
return obj_dict
示例4: __init__
def __init__(self, plane, base, nb_drop):
Command.__init__(self)
if plane is None or base is None:
raise "DropMilitarsCommand : Null reference"
self.planeSrc = plane
self.baseTarget = base
self.quantity = nb_drop
示例5: handle_messages
def handle_messages(self):
# Initialize DB
self.conn = sqlite3.connect('telegram.db')
self.c = self.conn.cursor()
# Create tables
self.c.execute('''create table if not exists Telegram (name STRING, last_name STRING, userid STRING UNIQUE)''')
while True:
print ("Waiting for message in queue")
message = self.queue.get()
user_info = message[1]
user_id = user_info[0]
first_name = user_info[1]
last_name = user_info[2]
if last_name is None:
last_name = "N/A"
print ("Got and handle message "+str(message.text))
res="Command not understood"
try:
#Extract the command
cmd_list = message.text.split()
if str(message.text) == "/start":
self.new_user(first_name, last_name, user_id)
continue
#Replace protocol command with OS command
cmd = commands.allowable_commands[cmd_list[0]]
cmd_list[0] = cmd
runner = Command(cmd_list)
runner.run(5)
print("RES "+str(runner.res)+" /RES")
self._send_message(message.sender.id, runner.res)
except Exception as e:
print ("Except: "+str(e))
示例6: __init__
def __init__(self, config):
Command.__init__(self, config)
if self.config.has_key('directory') and not os.path.isdir(self.config['directory']):
raise Exception("directory '%s' does not exists" % (self.config['directory'],))
if self.config.has_key('directory') and not os.listdir(self.config['directory']):
raise Exception("directory '%s' is empty" % (self.config['directory'],))
if not self.config.has_key('count'):
self.config['count'] = 1
示例7: execute
def execute(executor, *args, **kwargs):
ls_command = Command('ls')
for arg in args:
ls_command.add_argument(arg)
ls = type(executor)(reference=executor)
ls.add_command(ls_command)
return ls()
示例8: __init__
def __init__(self, plane, mil_qty, fuel_qty, delete):
Command.__init__(self)
if plane is None:
raise "LoadRessourcesCommand : Null reference"
self.planeSrc = plane
self.militarQuantity = mil_qty
self.fuelQuantity = fuel_qty
self.delete_ressources = delete
示例9: __init__
def __init__(self, fromDev, toDev, devType, group):
self.fromDev = fromDev
self.toDev = toDev
self.group = group
self.devType = devType
if devType == Link.CONTROLLER:
self.name = fromDev.name +" is controller for "+ Command.bToS(toDev)
else:
self.name = fromDev.name +" is a responder to "+ Command.bToS(toDev) +" Group: "+ group
示例10: Tray
class Tray(QtGui.QSystemTrayIcon):
def __init__(self, parent=None):
QtGui.QSystemTrayIcon.__init__(self, parent)
self.window = parent
self.setIcon(QtGui.QIcon("resources/img/icon.png"))
self.iconMenu = QtGui.QMenu(parent)
appactivate = self.iconMenu.addAction("Activate")
skyzoneMenu = QtGui.QMenu(self.iconMenu)
skyzoneMenu.setTitle("Skyzone")
self.iconMenu.addMenu(skyzoneMenu)
strikeMenu = QtGui.QMenu(self.iconMenu)
strikeMenu.setTitle("Strike")
self.iconMenu.addMenu(strikeMenu)
skyzonedevup = skyzoneMenu.addAction("Up Dev")
skyzoneupprod = skyzoneMenu.addAction("Up Prod")
strikedevup = strikeMenu.addAction("Up Dev")
strikeupprod = strikeMenu.addAction("Up Prod")
self.setContextMenu(self.iconMenu)
self.connect(appactivate,QtCore.SIGNAL('triggered()'),self.appActivate)
self.connect(skyzonedevup,QtCore.SIGNAL('triggered()'),self.skyzonedevup)
self.connect(strikedevup,QtCore.SIGNAL('triggered()'),self.strikedevup)
quitAction = QtGui.QAction("&Quit", self, triggered=QtGui.qApp.quit)
self.iconMenu.addAction(quitAction)
self.show()
def skyzonedevup(self):
self.thread = Command('Up Skyzone Dev')
self.window.printMessage('Up Skyzone Dev')
QtCore.QObject.connect(self.thread, QtCore.SIGNAL("executeCommandFinished(PyQt_PyObject, PyQt_PyObject)"), self.executeCommandFinished)
self.thread.start()
def strikedevup(self):
#self.window.createCommand('Up Strike Dev')
self.window.printMessage('Up Strike Dev')
self.thread = Command('Up Strike Dev')
QtCore.QObject.connect(self.thread, QtCore.SIGNAL("executeCommandFinished(PyQt_PyObject, PyQt_PyObject)"), self.executeCommandFinished)
self.thread.start()
def executeCommandFinished(self, command, result):
TooltipManage.create('Command', command, result)
def appActivate(self):
self.window.activate() # reffer Milana.py activate
示例11: run
def run(self):
while not self._stop:
#print "hasRun: " + str(self._hasRun) + ", command: " + str(self._command) + ", argument: " + str(self._argument)
if not self._hasRun and self._command is not None and self._argument is not None:
#print("executing command: " + self._command + " " + self._argument)
command = Command(self._command, self._argument)
self._scriptResponse = command.runAndGetOutputString()
self._hasRun = True
#print("result: " + str(self._scriptResponse))
else:
#print("not executing command")
time.sleep(0.1)
if DEBUG:
print("ending MultipleCommandExecutionThread")
示例12: run
def run(self):
logging.info('Kill old sessions.')
self.kill_tcp_processes()
logging.info('Starting sniffers.')
if FLAGS.sspath:
ss_log_name = '%s_%s_%s_%s.ss.log' % \
(self.carrier, self.browser, self.domain, str(time.time()))
ss_log_path = os.path.join(FLAGS.logdir, ss_log_name)
ss_fh = open(ss_log_path + '.tmp', 'w')
ss_log = subprocess.Popen([FLAGS.sspath,'-g'], stdout = ss_fh)
pcap_name = '%s_%s_%s_%s.pcap' % (self.carrier, self.browser, self.domain,
str(time.time()))
pcap_path = os.path.join(FLAGS.logdir, pcap_name)
pcap = subprocess.Popen(
['tcpdump','-i','%s' % self.interface,'-w', pcap_path + '.tmp'])
logging.info(str(['tcpdump','-i','%s' % self.interface,'-w', pcap_path]))
time.sleep(2)
logging.info('Starting browser.')
# TODO(tierney): Hacks to fix how we deal with non-terminating connections.
to_kill = None
if self.browser == 'chrome':
to_kill = 'chromedriver'
elif self.browser == 'firefox':
to_kill = '/usr/lib/firefox-10.0.2/firefox'
command = Command('./BrowserRun.py --browser %s --domain %s' % \
(self.browser, self.domain))
command.run(timeout = FLAGS.timeout, pskill = to_kill)
pcap.terminate()
os.rename(pcap_path +'.tmp', pcap_path)
if FLAGS.sspath:
ss_fh.flush()
ss_log.terminate()
ss_fh.flush()
ss_fh.close()
os.rename(ss_log_path + '.tmp', ss_log_path)
return
示例13: main_loop
def main_loop(self):
"""The loop through the lines of the input on which it does stuff. """
input = self.file
output = self.dest
#different namespaces may be used in a later version of the tool to be
# able to easily undefine a group of macro's
namespace = namespaces.NormalNameSpace()
#this linenumber is used in error messages
self.inputLineNo = 0
#this linenumber might later be available as a macro
self.outputLineNo = 0
if self.shebang:
self.inputLineNo += 1
line = input.readLine()
for line in input:
self.inputLineNo += 1
#when a command is not found, command and after are empty strings
(before, command, after) = self.command_split(line)
#check if the text is just followed or actually processed
lc = self.last_condition()
if lc:
#only output a line when there was more than whitespace before the
# command prefix, or when the empty_line option is True.
if (before.strip() != ""
or (self.options["empty_line"] and command == "")):
output.write(self.replace_object_macro(namespace, before))
self.outputLineNo += 1
#check if the command here is to be ignored
if (command != "" and Command.command_allowed(command, lc)):
try:
Command.get_command_func(command)(namespace, after,
self.last_condition, self.conditions, self.else_found)
except ValueError as e:
self.error(e.args[0])
except IndexError as e:
self.error(e.args[0])
示例14: download
def download(uri, dirname=None, output=None):
if dirname is None:
dirname = os.getcwd()
if output is None:
output = '/dev/null'
dest_path = os.path.join(dirname, os.path.basename(uri))
cmd = get_download_command(uri, dest_path, output)
if cmd is None:
return False
command = Command(cmd, dirname)
try:
command.run()
except:
return False
return os.path.exists(dest_path)
示例15: traverseAldb
def traverseAldb(self, startAddress):
while startAddress > 0x00:
print("Checking: 0x%0.2x" % startAddress)
SerialInstance().ser.flushInput()
SerialInstance().ser.flushOutput()
Command.queryMemory(self.deviceId, bytes([0x0F, startAddress]))
i = SerialInstance().ser.readline()
sleep(.3)
#Keep reading the address until we don't get a NACK
if re.search(r'(\w)+(15)\b', Command.bToS(i)):
print('Received NACK')
continue #This makes it stop here and try again
elif re.search(r'(\w)+(06)\b', Command.bToS(i)):
for _ in range(50):
SerialInstance().ser.flushInput()
SerialInstance().ser.flushOutput()
i = SerialInstance().ser.readline()
cmdStr = Command.bToS(i)
if len(i) > 0:
print("06: %s" % cmdStr)
if (len(i) > 0 and len(cmdStr) == 50):
self.addToAldb(i)
startAddress = startAddress - 0x08
print("address Decremented")
break
if re.search(r'(\w)+0(0|1)0000000000000000(\w\w){0,1}\b', Command.bToS(i)):
print("Found blank address: %02x" % startAddress)
return bytearray([i[13], i[14]])