当前位置: 首页>>代码示例>>Python>>正文


Python Server.run方法代码示例

本文整理汇总了Python中server.Server.run方法的典型用法代码示例。如果您正苦于以下问题:Python Server.run方法的具体用法?Python Server.run怎么用?Python Server.run使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在server.Server的用法示例。


在下文中一共展示了Server.run方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _display_from_interpreter

# 需要导入模块: from server import Server [as 别名]
# 或者: from server.Server import run [as 别名]
 def _display_from_interpreter(self):
     server = Server(json=self.saved_json_file)
     print '''Your visualization is being rendered at
              http://localhost:%s/
              Visit the url in your webgl compatible browser
              to see the animation in full glory'''%(server.port)
     server.run()
开发者ID:pramttl,项目名称:pydy-viz,代码行数:9,代码来源:scene.py

示例2: start

# 需要导入模块: from server import Server [as 别名]
# 或者: from server.Server import run [as 别名]
def start(args, kill = None):
    config_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), "pywps.cfg")

    processes = [
        FeatureCount(),
        SayHello(),
        Centroids(),
        UltimateQuestion(),
        Sleep(),
        Buffer(),
        Area(),
        Box(),
        Warp()
    ]

    s = Server(processes=processes, config_file=config_file)

    # TODO: need to spawn a different process for different server
    if args.waitress:
        import waitress
        from pywps import configuration

        configuration.load_configuration(config_file)
        host = configuration.get_config_value('wps', 'serveraddress').split('://')[1]
        port = int(configuration.get_config_value('wps', 'serverport'))

        waitress.serve(s.app, host=host, port=port)
    else:
        s.run()
开发者ID:jachym,项目名称:pywps-4-demo,代码行数:31,代码来源:demo.py

示例3: main

# 需要导入模块: from server import Server [as 别名]
# 或者: from server.Server import run [as 别名]
def main():
    import argparse

    parser = argparse.ArgumentParser()
    parser.add_argument('-w', '--waitress', action='store_true')
    args = parser.parse_args()

    config_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), "pywps.cfg")

    processes = [
        FeatureCount(),
        SayHello(),
        Centroids(),
        UltimateQuestion(),
        Sleep(),
        Buffer(),
        Area(),
        Viewshed()
    ]

    s = Server(processes=processes, config_file=config_file)

    # TODO: need to spawn a different process for different server
    if args.waitress:
        import waitress
        from pywps import configuration

        configuration.load_configuration(config_file)
        host = configuration.get_config_value('wps', 'serveraddress').split('://')[1]
        port = int(configuration.get_config_value('wps', 'serverport'))

        waitress.serve(s.app, host=host, port=port)
    else:
        s.run()
开发者ID:keceke,项目名称:pywps,代码行数:36,代码来源:demo.py

示例4: foreGround

# 需要导入模块: from server import Server [as 别名]
# 或者: from server.Server import run [as 别名]
def foreGround(clt, args):
    # --
    if "session_object" not in args:
        return
    session = args["session_object"]
    # --
    # Wait until gui is arrived
    # tmax = nbtot * dt
    # --
    gui_detected = False
    dt = 0.1
    nbtot = 100
    nb = 0
    while 1:
        try:
            status = session.GetStatSession()
            gui_detected = status.activeGUI
        except:
            pass
        if gui_detected:
            break
        from time import sleep
        sleep(dt)
        nb += 1
        if nb == nbtot:
            break
        pass
    # --
    if not gui_detected:
        return
    # --
    from salome_utils import getPortNumber
    port = getPortNumber()
    # --
    server = Server({})
    if sys.platform == "win32":
      server.CMD = [os.getenv("PYTHONBIN"), "-m", "killSalomeWithPort", "--spy", "%s"%(os.getpid()), "%s"%(port)]
    else:
      server.CMD = ["killSalomeWithPort.py", "--spy", "%s"%(os.getpid()), "%s"%(port)]
    server.run()
    # os.system("killSalomeWithPort.py --spy %s %s &"%(os.getpid(), port))
    # --
    dt = 1.0
    try:
        while 1:
            try:
                status = session.GetStatSession()
                assert status.activeGUI
            except:
                break
            from time import sleep
            sleep(dt)
            pass
        pass
    except KeyboardInterrupt:
        from killSalomeWithPort import killMyPort
        killMyPort(port)
        pass
    return
开发者ID:FedoraScientific,项目名称:salome-kernel,代码行数:61,代码来源:runSalome.py

示例5: _serverThread

# 需要导入模块: from server import Server [as 别名]
# 或者: from server.Server import run [as 别名]
class _serverThread( Thread ):
	def __init__( self, port=6543, handler=catcher ):
		Thread.__init__(self)
		
		self.server = Server( port, handler, tryagain=True )
		
	def run( self ):
		self.server.run()
  
  
  	def kill( self ):
  		self.server.kill()
开发者ID:srswinde,项目名称:py-dataserver,代码行数:14,代码来源:dataserver.py

示例6: main

# 需要导入模块: from server import Server [as 别名]
# 或者: from server.Server import run [as 别名]
def main(config=None, label=None):
    # Setup PDF Generator
    pdf = PDF("A4")

    # Start initial page, always one
    pdf.add_page()

    # Command run from console with label input
    # Generate label and exit
    if label:
        # Add all fonts here
        pdf.add_font("cambria", "", "fonts/cambria.ttf", True)
        pdf.add_font("cambria", "B", "fonts/cambria_B.ttf", True)
        pdf.generate(**label)
        return

    if config:
        server = Server(config, pdf)
        server.run()
开发者ID:phelian,项目名称:clg,代码行数:21,代码来源:clg.py

示例7: main

# 需要导入模块: from server import Server [as 别名]
# 或者: from server.Server import run [as 别名]
def main():
  # id = 0
  # #separate process from the terminal that started it
  # try:
  #   id =  os.fork()
  #   print 'forked'
  # except OSError, e:
  #   #if there was an error while forking exit both processes
  #   print e
  #   sys.exit(1)

  # #if process is not child, exit
  # if id != 0:
  #   sys.exit(0)

  # print 'parent process ended'

  # os.setsid()


  #create and run server
  server = Server() 
  server.run()
开发者ID:SDSMT-CSC,项目名称:SDSC,代码行数:25,代码来源:main.py

示例8: Client

# 需要导入模块: from server import Server [as 别名]
# 或者: from server.Server import run [as 别名]

#.........这里部分代码省略.........
                tp['resume_data']=resume_data

        elif uri.startswith('magnet:'):
            tp={'url':uri}
            resume_data=self._cache.get_resume(info_hash=Cache.hash_from_magnet(uri))
            if resume_data:
                tp['resume_data']=resume_data

        elif os.path.isfile(uri):
            if os.access(uri,os.R_OK):
                info = lt.torrent_info(uri)
                tp= {'ti':info}
                resume_data= self._cache.get_resume(info_hash=str(info.info_hash()))
                if resume_data:
                    tp['resume_data']=resume_data
            else:
                raise ValueError('Invalid torrent path %s' % uri)
        else:
            raise ValueError("Invalid torrent %s" %uri)
        
        tp.update(self.torrent_paramss)
        self._th = self._ses.add_torrent(tp)
        

        for tr in self.INITIAL_TRACKERS:
            self._th.add_tracker({'url':tr})

        self._th.set_sequential_download(True)
        self._th.force_reannounce()
        self._th.force_dht_announce()

        self._monitor.start()
        self._dispatcher.do_start(self._th, self._ses)
        self.server.run()

        
    def stop(self):
        """
        Función encargada de de detener el torrent y salir
        """
        self._dispatcher.stop()
        self._dispatcher.join()
        self._monitor.stop()
        self.server.stop()
        self._dispatcher.stop()
        if self._ses:
            self._ses.pause()
            if self._th:
                self.save_resume()
            self.save_state()
        self._stop_services()
        self._ses.remove_torrent(self._th, self.auto_delete)
        del self._ses
        self.closed = True

    def _start_services(self):
        """
        Función encargada de iniciar los servicios de libtorrent: dht, lsd, upnp, natpnp
        """
        self._ses.add_dht_router("router.bittorrent.com",6881)
        self._ses.add_dht_router("router.bitcomet.com",554)
        self._ses.add_dht_router("router.utorrent.com",6881)
        self._ses.start_dht()
        self._ses.start_lsd()
        self._ses.start_upnp()
        self._ses.start_natpmp()
开发者ID:SpankyEsse,项目名称:plugin.video.streamondemand,代码行数:70,代码来源:client.py

示例9: Server

# 需要导入模块: from server import Server [as 别名]
# 或者: from server.Server import run [as 别名]
#       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, write to the Free Software
#       Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#       MA 02110-1301, USA.

import socket
import time

from select import select

import config
from server import Server
import channel
import user

if __name__ == "__main__":
    server = Server()
    try:
        server.run()
    #except Exception, e:
    #    print e
    except KeyboardInterrupt:
        pass
    finally:
        server.shutdown()
开发者ID:carriercomm,项目名称:omgircd,代码行数:32,代码来源:ircd.py

示例10: run

# 需要导入模块: from server import Server [as 别名]
# 或者: from server.Server import run [as 别名]
 def run(self):
     s = Server(self.args.port)
     s.run()
开发者ID:cletusw,项目名称:goal-e,代码行数:5,代码来源:echoserver.py

示例11: main

# 需要导入模块: from server import Server [as 别名]
# 或者: from server.Server import run [as 别名]
def main():
    try:
        init_options()
    except OptionsError as e:
        sys.stderr.write("Error: {0}\n\n".format(e))
        sys.stderr.write(usage())
        sys.stderr.write("\n");
        sys.stderr.flush()
        sys.exit(os.EX_CONFIG)
        
    if options.main.generate_config:
        print(generate_sample_config()) # XXX: this doesn't yet work properly because of groper
        sys.exit()

    conf_root = os.path.dirname(os.path.abspath(options.main.config))

    facility_db = FacilityDB()
    try:
        facility_db.load_config(normalize_path(options.main.facilities_config, conf_root))
    except (IOError) as e:
        sys.stderr.write("Error reading {0}: {1}\n".format(options.main.facilities_config, e))
        sys.stderr.flush()
        sys.exit(os.EX_CONFIG)
    except (FacilityError, configparser.Error) as e:
        sys.stderr.write("{0} contains errors:\n\n".format(options.main.facilities_config))

        if hasattr(e, 'lineno'):
            e = 'Error on line {0}: {1}'.format(e.lineno, e.message.split("\n")[0].strip())

        sys.stderr.write("{0}\n\n".format(e))
        sys.stderr.write("Exiting now.\n")
        sys.stderr.flush()
        sys.exit(os.EX_CONFIG)

    if options.main.check_config:
        sys.exit() # We are just checking the config file, so exit here.

    cache_config_checksum()
    create_dirs()

    if options.main.daemon:
        daemonize()

    if options.main.user:
        drop_privileges(options.main.user)

    if options.main.pidfile:
        write_pid(options.main.pidfile)
        atexit.register(exit_handler)

    setup_logging()

    try:
        logging.getLogger().info("Starting loghogd.")

        compressor = Compressor()
        compressor.find_uncompressed(options.main.logdir, r'.+\.log\..+')

        writer = Writer(facility_db, compressor, options.main.logdir)
        processor = Processor(facility_db, writer)

        server = Server(processor.on_message, conf_root)

        signal_handler = make_shutdown_handler(server, writer, compressor)

        signal.signal(signal.SIGINT, signal_handler)
        signal.signal(signal.SIGTERM, signal_handler)
        
        signal.signal(signal.SIGHUP, make_reload_handler(facility_db, writer))
    except Exception as e:
        logging.getLogger().error(e)
        logging.getLogger().error('Exiting abnormally due to an error at startup.')
        sys.exit(os.EX_CONFIG)

    try:
        compressor.start()
        server.run()
    except Exception as e:
        logging.getLogger().exception(e)
        logging.getLogger().error('Exiting abnormally due to an error at runtime.')
        shutdown(None, server, writer, compressor)
        sys.exit(os.EX_SOFTWARE)
    
    logging.getLogger().info('Shutdown complete. Exiting.')
开发者ID:activefrequency,项目名称:loghogd,代码行数:86,代码来源:main.py

示例12: Client

# 需要导入模块: from server import Server [as 别名]
# 或者: from server.Server import run [as 别名]
class Client(object):
    VIDEO_EXTS = {'.avi': 'video/x-msvideo', '.mp4': 'video/mp4', '.mkv': 'video/x-matroska',
                  '.m4v': 'video/mp4', '.mov': 'video/quicktime', '.mpg': 'video/mpeg','.ogv': 'video/ogg',
                  '.ogg': 'video/ogg', '.webm': 'video/webm', '.ts': 'video/mp2t', '.3gp': 'video/3gpp'}

    def __init__(self, url, port=None, ip=None, auto_shutdown=True, wait_time=20, timeout=5, is_playing_fnc=None):

        self.port = port if port else random.randint(8000,8099)
        self.ip = ip if ip else "127.0.0.1"
        self.connected = False
        self.start_time = None
        self.last_connect = None
        self.is_playing_fnc = is_playing_fnc
        self.auto_shutdown =  auto_shutdown
        self.wait_time =  wait_time
        self.timeout =  timeout
        self.running = False
        self.file = None
        self.files = []

        self._server = Server((self.ip, self.port), Handler, client=self)
        self.add_url(url)
        self.start()

    def start(self):
        self.start_time = time.time()
        self.running = True
        self._server.run()
        t= Thread(target=self._auto_shutdown)
        t.setDaemon(True)
        t.start()
        logger.info("MEGA Server Started")

    def _auto_shutdown(self):
        while self.running:
            time.sleep(1)
            if self.file and self.file.cursor:
                self.last_connect = time.time()

            if self.is_playing_fnc and  self.is_playing_fnc():
                self.last_connect = time.time()

            if self.auto_shutdown:
                #shudown por haber cerrado el reproductor
                if self.connected and self.last_connect and self.is_playing_fnc and not self.is_playing_fnc():
                    if time.time() - self.last_connect - 1 > self.timeout:
                        self.stop()

                #shutdown por no realizar ninguna conexion
                if (not self.file or not self.file.cursor) and self.start_time and self.wait_time and not self.connected:
                    if time.time() - self.start_time - 1 > self.wait_time:
                        self.stop()

                #shutdown tras la ultima conexion
                if (not self.file or not self.file.cursor) and self.timeout and self.connected and self.last_connect and not self.is_playing_fnc:
                    if time.time() - self.last_connect - 1 > self.timeout:
                        self.stop()

    def stop(self):
        self.running = False
        self._server.stop()
        logger.info("MEGA Server Stopped")

    def get_play_list(self):
        if len(self.files) > 1:
            return "http://" + self.ip + ":" + str(self.port) + "/playlist.pls"
        else:
            return "http://" + self.ip + ":" + str(self.port) + "/" + urllib.quote(self.files[0].name.encode("utf8"))

    def get_files(self):
        files = []
        if self.files:
            for file in self.files:
                n = file.name.encode("utf8")
                u = "http://" + self.ip + ":" + str(self.port) + "/" + urllib.quote(n)
                s = file.size
                file_id = file.file_id
                files.append({"name":n,"url":u,"size":s, "id": file_id})
        return files

    def add_url(self, url):
        url = url.split("/#")[1]
        id_video = None
        if "|" in url:
            url, id_video = url.split("|")
        if url.startswith("F!"):
            if len(url.split("!")) ==3:
                folder_id = url.split("!")[1]
                folder_key = url.split("!")[2]
                master_key = self.base64_to_a32(folder_key)
                files = self.api_req({"a":"f","c":1,"r":1},"&n="+folder_id)
                for file in files["f"]:
                 if file["t"] == 0:
                    if id_video and id_video != file["h"]:
                        continue
                    key = file['k'][file['k'].index(':') + 1:]
                    key = self.decrypt_key(self.base64_to_a32(key), master_key)
                    k = (key[0] ^ key[4], key[1] ^ key[5], key[2] ^ key[6], key[3] ^ key[7])
                    attributes = self.base64urldecode(file['a'])
                    attributes = self.dec_attr(attributes, k)
#.........这里部分代码省略.........
开发者ID:FusionwareIT,项目名称:Repository-FusionBox,代码行数:103,代码来源:client.py

示例13: __init__

# 需要导入模块: from server import Server [as 别名]
# 或者: from server.Server import run [as 别名]
class ServerTester:
    def __init__(self):
        self.server = Server()

    def test_get_stimuli_urls(self):
        url = 'http://52.24.142.90/stimuli_data/Jan29/'
        result = self.server.get_stimuli_urls(url)
        assert result[0] == 'http://52.24.142.90/stimuli_data/Jan29/test_data1.txt'
        assert result[1] == 'http://52.24.142.90/stimuli_data/Jan29/test_data2.txt'
        assert result[2] == 'http://52.24.142.90/stimuli_data/Jan29/test_data3.txt'

    def test_GET(self):
        client_thread = threading.Thread(target=self.test_GET_client_func)
        client_thread.start()
        self.server.run()

    def test_PEND(self):
        client_thread = threading.Thread(target=self.test_PEND_client_func)
        client_thread.start()
        self.server.run()

    def test_COMPLETE(self):
        client_thread = threading.Thread(target=self.test_COMPLETE_client_func)
        client_thread.start()
        self.server.run()

    def test_checkfail(self):
        stimuli_urls = [key for key in self.server.stimuli_info_dict.keys()]
        self.server.mark_stimuli_status(stimuli_urls[0], 'pending')
        for i in range(0, self.server.allowed_pending_gap + 5):
            sleep(1)
            if i < self.server.allowed_pending_gap:
                assert self.server.stimuli_info_dict[stimuli_urls[0]]['status'] == 'pending'
            else:
                assert self.server.stimuli_info_dict[stimuli_urls[0]]['status'] == 'waiting'

    def test_GET_client_func(self):
        sleep(2)

        client = test_client.Client()
        stimuli_url = client.run('GET=-=')
        assert stimuli_url in self.server.stimuli_info_dict
        assert self.server.stimuli_info_dict[stimuli_url]['status'] == 'waiting'

        print 'Client side is done'

    def test_PEND_client_func(self):
        sleep(2)

        client = test_client.Client()
        stimuli_url = client.run('GET=-=')

        client = test_client.Client()
        client.run('PEND=-=' + stimuli_url)
        assert self.server.stimuli_info_dict[stimuli_url]['status'] == 'pending'

        print 'Client side is done'

    def test_COMPLETE_client_func(self):
        sleep(2)

        client = test_client.Client()
        stimuli_url = client.run('GET=-=')

        client = test_client.Client()
        client.run('PEND=-=' + stimuli_url)
        assert self.server.stimuli_info_dict[stimuli_url]['status'] == 'pending'

        client = test_client.Client()
        client.run('COMPLETE=-=' + stimuli_url)
        assert self.server.stimuli_info_dict[stimuli_url]['status'] == 'completed'

        print 'Client side is done'

    def test_checkfail_client_func(self):
        sleep(2)

        client = test_client.Client()
        stimuli_url = client.run('GET=-=')

        client = test_client.Client()
        client.run('PEND=-=' + stimuli_url)

        for i in range(0, self.server.allowed_pending_gap + 5):
            sleep(1)
            print 'Sleeped ' + str(i) + 'th second.'
            print 'status: ' + self.server.stimuli_info_dict[stimuli_url]['status']
            # if i < self.server.allowed_pending_gap:
            #     assert self.server.stimuli_info_dict[stimuli_url]['status'] == 'pending'
            # else:
            #     assert self.server.stimuli_info_dict[stimuli_url]['status'] == 'waiting'

        print 'Client side is done'

    def test_integration(self):

        worker1_get_client

        worker2_get_client = test_client.Client()
        worker2_accept_client = test_client.Client()
#.........这里部分代码省略.........
开发者ID:habemusne,项目名称:simi_server,代码行数:103,代码来源:server_tester.py

示例14: main

# 需要导入模块: from server import Server [as 别名]
# 或者: from server.Server import run [as 别名]
def main():
    s = Server()
    try:
        s.run()
    except KeyboardInterrupt:
        print "Ctr-C pressed, exiting"
开发者ID:mcarter,项目名称:csp_eventlet_jsio_example,代码行数:8,代码来源:start.py

示例15: Client

# 需要导入模块: from server import Server [as 别名]
# 或者: from server.Server import run [as 别名]

#.........这里部分代码省略.........
                tp['resume_data']=resume_data

        elif uri.startswith('magnet:'):
            tp={'url':uri}
            resume_data=self._cache.get_resume(info_hash=Cache.hash_from_magnet(uri))
            if resume_data:
                tp['resume_data']=resume_data

        elif os.path.isfile(uri):
            if os.access(uri,os.R_OK):
                info = lt.torrent_info(uri)
                tp= {'ti':info}
                resume_data= self._cache.get_resume(info_hash=str(info.info_hash()))
                if resume_data:
                    tp['resume_data']=resume_data
            else:
                raise ValueError('Invalid torrent path %s' % uri)
        else:
            raise ValueError("Invalid torrent %s" %uri)
        
        tp.update(self.torrent_paramss)
        self._th = self._ses.add_torrent(tp)
        

        for tr in self.INITIAL_TRACKERS:
            self._th.add_tracker({'url':tr})

        self._th.set_sequential_download(True)
        self._th.force_reannounce()
        self._th.force_dht_announce()

        self._monitor.start()
        self._dispatcher.do_start(self._th, self._ses)
        self.server.run()

        
    def stop(self):
        self._dispatcher.stop()
        self._dispatcher.join()
        self._monitor.stop()
        self.server.stop()
        self._dispatcher.stop()
        if self._ses:
            self._ses.pause()
            if self._th:
                self.save_resume()
            self.save_state()
        self._stop_services()
        self._ses.remove_torrent(self._th, self.auto_delete)
        del self._ses
        self.closed = True

    def _start_services(self):
        self._ses.add_dht_router("router.bittorrent.com",6881)
        self._ses.add_dht_router("router.bitcomet.com",554)
        self._ses.add_dht_router("router.utorrent.com",6881)
        self._ses.start_dht()
        self._ses.start_lsd()
        self._ses.start_upnp()
        self._ses.start_natpmp()
        
        
    def _stop_services(self):
        self._ses.stop_natpmp()
        self._ses.stop_upnp()
        self._ses.stop_lsd()
开发者ID:neozeta,项目名称:plugin.video.streamondemand,代码行数:70,代码来源:client.py


注:本文中的server.Server.run方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。