本文整理汇总了Python中server.Server.stop方法的典型用法代码示例。如果您正苦于以下问题:Python Server.stop方法的具体用法?Python Server.stop怎么用?Python Server.stop使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类server.Server
的用法示例。
在下文中一共展示了Server.stop方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: TestSendfile
# 需要导入模块: from server import Server [as 别名]
# 或者: from server.Server import stop [as 别名]
class TestSendfile(unittest.TestCase):
def setUp(self):
# server
self.server = Server(('127.0.0.1', int(GATEWAY_DAT_PORT)))
self.server.start()
# client
self.client = socket.socket()
self.client.connect((self.server.host, self.server.port))
self.client.settimeout(10)
#self.client.recv(1024)
self.sockno = self.client.fileno()
self.file = open('10MB', 'rb')
self.fileno = self.file.fileno()
def tearDown(self):
#save_remove('10MB-1')
self.file.close()
self.client.close()
if self.server.running:
self.server.stop()
self.server = None # garbage collection
def test_send_file(self):
total_sent = 0
while True:
sent = self.file.read(BUFFER_LEN)
if not sent:
break #EOF
self.client.sendall(sent)
self.client.close()
self.server.wait()
data = self.server.handler_instance.get_data()
print 'Server received: %s' % len(data)
示例2: run_all
# 需要导入模块: from server import Server [as 别名]
# 或者: from server.Server import stop [as 别名]
def run_all(self):
"""For each file in the test suite, run client program
assuming each file represents an individual test."""
try:
server = Server(self.ini["core"], self.ini["module"])
except Exception as e:
print e
raise RuntimeError("Unknown server: core = {0}, module = {1}".format(
self.ini["core"], self.ini["module"]))
if len(self.tests) == 0:
# noting to test, exit
return 0
server.deploy(self.ini["config"],
server.find_exe(self.args.builddir, silent=False),
self.args.vardir, self.args.mem, self.args.start_and_exit,
self.args.gdb, self.args.valgrind,
init_lua=self.ini["init_lua"], silent=False)
if self.args.start_and_exit:
print " Start and exit requested, exiting..."
exit(0)
longsep = "=============================================================================="
shortsep = "------------------------------------------------------------"
print longsep
print string.ljust("TEST", 48), "RESULT"
print shortsep
failed_tests = []
self.ini["server"] = server
for test in self.tests:
sys.stdout.write(string.ljust(test.name, 48))
# for better diagnostics in case of a long-running test
sys.stdout.flush()
test_name = os.path.basename(test.name)
if test_name in self.ini["disabled"]:
print "[ skip ]"
elif not server.debug and test_name in self.ini["release_disabled"]:
print "[ skip ]"
elif self.args.valgrind and test_name in self.ini["valgrind_disabled"]:
print "[ skip ]"
else:
test.run(server)
if not test.passed():
failed_tests.append(test.name)
print shortsep
if len(failed_tests):
print "Failed {0} tests: {1}.".format(len(failed_tests),
", ".join(failed_tests))
server.stop(silent=False)
server.cleanup()
if self.args.valgrind and check_valgrind_log(server.valgrind_log):
print " Error! There were warnings/errors in valgrind log file:"
print_tail_n(server.valgrind_log, 20)
return 1
return len(failed_tests)
示例3: main
# 需要导入模块: from server import Server [as 别名]
# 或者: from server.Server import stop [as 别名]
def main():
# Build the library
subprocess.call(['npm', 'run', 'build'])
# Copy the library to the http server path
subprocess.call([
'cp',
join(BASEDIR, '..', 'dist/ether.global.js'),
join(BASEDIR, 'public')
])
# Build the sample user app under test
# Building the app only works if dir is set properly
os.chdir(BASEDIR)
subprocess.call(['node', join(BASEDIR, 'rollup.js')])
# Start the http server
httpd = Server()
httpd.start()
# Run CasperJS tests
subprocess.call([
join(BASEDIR, '..', 'node_modules/casperjs/bin/casperjs'),
'test', '--log-level=debug', '--verbose',
join(BASEDIR, 'test')
])
# Stop the http server
httpd.stop()
示例4: main
# 需要导入模块: from server import Server [as 别名]
# 或者: from server.Server import stop [as 别名]
def main():
parser = argparse.ArgumentParser(
description="This is the DMCR Frontend. For licensing see LICENSE.txt.", add_help=False
)
parser.add_argument("--file", "-f", default="../../scenes/scene.json")
parser.add_argument("--width", "-w", default=800)
parser.add_argument("--height", "-h", default=600)
parser.add_argument("--iterations", "-i", default=5)
parser.print_help()
params = vars(parser.parse_args())
print "Starting FE server with:\n{file}: {width}x{height}, {iterations} iterations".format(**params)
server = Server()
server.FileToTask(params["file"], int(params["width"]), int(params["height"]), int(params["iterations"]))
try:
server.start()
while True:
choice = raw_input("> ")
if choice == "l":
for task in server.taskmanager.ListTasks():
print str(task)
elif choice == "s":
task_id = raw_input("Task ID: ")
server.taskmanager.StopTask(int(task_id))
elif choice == "a":
filename = raw_input("Filename: ")
width = 800
height = 600
iterations = 5
width_i = raw_input("Width (800): ")
if width_i != "":
width = int(width_i)
height_i = raw_input("Height (600): ")
if height_i != "":
height = int(height_i)
iterations_i = raw_input("Iterations (5): ")
if iterations_i != "":
iterations = int(iterations_i)
server.FileToTask(filename, width, height, iterations)
elif choice == "q":
break
else:
print "l: list tasks\na: add task\ns: stop task\nq: quit"
except KeyboardInterrupt as e:
print "DMCR.main(): Excepted, quitting", e
finally:
print "Stopping server"
server.stop()
server.taskmanager.stop() # wait for tasks to finish
示例5: main
# 需要导入模块: from server import Server [as 别名]
# 或者: from server.Server import stop [as 别名]
def main():
args = parse_args()
config = parse_config(args.config, args)
print('Starting server on %s:%s.' % (config['server']['bind'], config['server']['port']))
print('Server root: %s' % config['server']['webroot'])
if args.daemon:
daemonize(config)
server = Server(config)
try:
server.serve()
except KeyboardInterrupt:
server.stop()
示例6: SjsServer
# 需要导入模块: from server import Server [as 别名]
# 或者: from server.Server import stop [as 别名]
class SjsServer(object):
@tornado.gen.engine
def __init__(self, config):
self.server = Server('sjs', config)
yield tornado.gen.Task(self.server.connect)
conn_maker = functools.partial(Connection, self.server)
router = sockjs.tornado.SockJSRouter(conn_maker, '/sjs')
app = tornado.web.Application(router.urls)
app.listen(config.sockjs_port)
def stop(self):
self.server.stop()
示例7: main
# 需要导入模块: from server import Server [as 别名]
# 或者: from server.Server import stop [as 别名]
def main():
try:
#Read config file
settings=Settings()
#Set up logger
logger=Logger(settings)
#Create scanner
server=Server(settings,logger)
#Begin scanning
server.start()
except KeyboardInterrupt:
server.stop()
示例8: __init__
# 需要导入模块: from server import Server [as 别名]
# 或者: from server.Server import stop [as 别名]
class Runner:
def __init__(self):
self.server = None
self.init_logging()
signal.signal(signal.SIGINT, self.stop)
signal.signal(signal.SIGTERM, self.stop)
def init_logging(self):
if not hasattr(settings, 'Logging'):
logging.basicConfig(format='[%(threadName)s @ %(asctime)s] %(levelname)s: %(message)s', level='DEBUG')
return
logger = logging.getLogger()
logger.setLevel(settings.Logging.level)
formatter = logging.Formatter(settings.Logging.format)
if settings.Logging.output_file:
fileHandler = logging.FileHandler(settings.Logging.output_file)
fileHandler.setFormatter(formatter)
logger.addHandler(fileHandler)
if settings.Logging.console_output:
consoleHandler = logging.StreamHandler()
consoleHandler.setFormatter(formatter)
logger.addHandler(consoleHandler)
def start(self):
handler = Handler()
self.server = Server(settings.ServerSettings, handler)
try:
self.server.start()
except Exception as e:
logging.error('Caught error: {}'.format(str(e)))
if self.server:
self.server.stop()
sys.exit(1)
def stop(self, signal, frame):
if self.server:
self.server.stop()
sys.exit(0)
else:
logging.warning('Cannot stop server because it isn\'t running.')
sys.exit(9)
示例9: main
# 需要导入模块: from server import Server [as 别名]
# 或者: from server.Server import stop [as 别名]
def main():
server = Server()
while True:
# create server
sys.stdout.write("WYBO server> ")
cmd = sys.stdin.readline()
if cmd == "start\n":
server.start(9003)
elif cmd == "stop\n":
server.stop()
elif cmd == "restart\n" or cmd == "reboot\n":
server.reboot()
elif cmd == "adduser\n":
server.add_user()
elif cmd == "exit\n":
server.stop()
exit()
示例10: TCPServer
# 需要导入模块: from server import Server [as 别名]
# 或者: from server.Server import stop [as 别名]
class TCPServer(tornado.tcpserver.TCPServer):
@tornado.gen.engine
def __init__(self, config):
super(TCPServer, self).__init__()
self.server = Server('tcp', config)
yield tornado.gen.Task(self.server.connect)
logging.info('Starting IRCd server on port \'%d\'', config.tcp_port)
self.listen(config.tcp_port)
def stop(self):
self.server.stop()
def handle_stream(self, stream, address):
tag = self.server.make_tag(address[0], address[1])
u_handler = functools.partial(self.handle_user_data, tag)
stream.read_until_close(u_handler, u_handler)
s_handler = functools.partial(self.handle_server_data, tag, stream)
self.server.user_connect(tag, address[0], s_handler)
def handle_user_data(self, tag, data):
if data:
self.server.user_message(tag, data)
else:
self.server.user_disconnect(tag)
def handle_server_data(self, tag, stream, data):
try:
if data:
# this might fail if the connection is closed
stream.write(data)
else:
stream.close()
except:
# close and notify closed
try:
stream.close()
finally:
self.server.user_disconnect(tag)
示例11: run_monitor
# 需要导入模块: from server import Server [as 别名]
# 或者: from server.Server import stop [as 别名]
def run_monitor():
local_address = (sys.argv[1], int(sys.argv[2]))
servers = [(addr, port) for addr, port in settings.SERVER_LIST if addr != local_address[0] or port != local_address[1]]
stats = Stats(local_address)
stats.start()
server = Server(local_address)
server.start()
client_pool = ClientPool(servers, stats)
client_pool.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
server.stop()
client_pool.stop()
stats.stop()
示例12: main
# 需要导入模块: from server import Server [as 别名]
# 或者: from server.Server import stop [as 别名]
#.........这里部分代码省略.........
#TODO: save screenshot
gui.set_status_stats(False)
gui.set_status_game(False)
gui.set_stats({})
continue
# =========================================
# Stats
# =========================================
try:
results = get_stats(screenshot)
except:
#TODO: save screenshot
results = None
if results is None:
gui.set_status_stats(False)
gui.set_stats({})
continue
# =========================================
# Stats Exist!
# =========================================
if not game_started:
game_started = True
socket_server.send({ 'event': 'game_started' })
gui.set_status_stats(True)
gui.set_stats(results)
if results['team_kills'] > 200 or results['team_deaths'] > 200 or results['kills'] > 200:
broken += 1
screenshot.image.save('broken{}.bmp'.format(broken))
# =========================================
# Events
# =========================================
if last_results and results:
diff_cs = results['CS'] - last_results['CS']
diff_kills = results['kills'] - last_results['kills']
diff_deaths = results['deaths'] - last_results['deaths']
diff_team_kills = results['team_kills'] - last_results['team_kills']
diff_team_deaths = results['team_deaths'] - last_results['team_deaths']
if diff_team_kills < 0 or diff_team_deaths < 0 or diff_kills < 0:
broken += 1
screenshot.image.save('broken_before_{}.bmp'.format(broken))
last_screenshot.image.save('broken_after_{}.bmp'.format(broken))
if diff_cs > 0:
socket_server.send({ 'event': 'cs', 'amount': diff_cs, 'total': results['CS'] })
if diff_kills:
time_now = time()
time_since_last = time_now - kill_spree[0]
if time_since_last <= 10.5:
kill_spree = (time_now, kill_spree[1]+diff_kills)
else:
kill_spree = (time_now, 1)
kills = kill_spree[1]
socket_server.send({ 'event': 'kill', 'total': results['kills'], 'streak': kills })
elif diff_team_kills:
socket_server.send({ 'event': 'team_kill', 'amount': diff_team_kills, 'total': results['team_kills'] })
if diff_deaths:
socket_server.send({ 'event': 'death', 'total': results['deaths'] })
elif diff_team_deaths:
socket_server.send({ 'event': 'team_death', 'amount': diff_team_deaths, 'total': results['team_deaths'] })
last_results = results
last_screenshot = screenshot
# =========================================
# Missing Window
# =========================================
else:
if game_started:
game_started = False
last_results = None
socket_server.send({ 'event': 'game_finished' })
if game_open:
game_open = False
gui.set_status_game(False)
gui.set_stats({})
gui.set_status_clients(len(socket_server.clients()))
socket_server.stop()
示例13: __init__
# 需要导入模块: from server import Server [as 别名]
# 或者: from server.Server import stop [as 别名]
#.........这里部分代码省略.........
self.log.info("No new versions available.")
def checkForNewUpdate(self, type=None):
if type == None: type = globals.type
if type == "dev":
try:
r = requests.get("https://raw.githubusercontent.com/benbaptist/minecraft-wrapper/development/docs/version.json")
data = r.json()
if self.update:
if self.update > data["build"]: return False
if data["build"] > globals.build and data["type"] == "dev": return (data["version"], data["build"], data["type"])
else: return False
except:
self.log.warn("Failed to check for updates - are you connected to the internet?")
else:
try:
r = requests.get("https://raw.githubusercontent.com/benbaptist/minecraft-wrapper/master/docs/version.json")
data = r.json()
if self.update:
if self.update > data["build"]: return False
if data["build"] > globals.build and data["type"] == "stable": return (data["version"], data["build"], data["type"])
else: return False
except:
self.log.warn("Failed to check for updates - are you connected to the internet?")
return False
def performUpdate(self, version, build, type):
if type == "dev": repo = "development"
else: repo = "master"
try:
wrapperHash = requests.get("https://raw.githubusercontent.com/benbaptist/minecraft-wrapper/%s/docs/Wrapper.py.md5" % repo).text
wrapperFile = requests.get("https://raw.githubusercontent.com/benbaptist/minecraft-wrapper/%s/Wrapper.py" % repo).content
self.log.info("Verifying Wrapper.py...")
if hashlib.md5(wrapperFile).hexdigest() == wrapperHash:
self.log.info("Update file successfully verified. Installing...")
with open(sys.argv[0], "w") as f:
f.write(wrapperFile)
self.log.info("Wrapper.py %s (#%d) installed. Please reboot the Wrapper.py." % (".".join([str(_) for _ in version]), build))
self.update = build
return True
else:
return False
except:
self.log.error("Failed to update due to an internal error:")
self.log.getTraceback()
return False
def timer(self):
while not self.halt:
self.callEvent("timer.second", None)
time.sleep(1)
def console(self):
while not self.halt:
input = raw_input("")
if len(input) < 1: continue
if input[0] is not "/":
try:
self.server.console(input)
except:
break
continue
def args(i):
try: return input[1:].split(" ")[i];
except:pass;
command = args(0)
if command == "halt":
self.server.stop("Halting server...")
self.halt = True
sys.exit()
elif command == "stop":
self.server.stop("Stopping server...")
elif command == "start":
self.server.start()
elif command == "restart":
self.server.stop("Server restarting, be right back!")
elif command == "reload":
self.reloadPlugins()
elif command == "update-wrapper":
self.checkForUpdate(False)
elif command == "plugins":
self.log.info("List of Wrapper.py plugins installed:")
for id in self.plugins:
plugin = self.plugins[id]
if plugin["good"]:
name = plugin["name"]
summary = plugin["summary"]
if summary == None: summary = "No description available for this plugin"
version = plugin["version"]
self.log.info("%s v%s - %s" % (name, ".".join([str(_) for _ in version]), summary))
else:
self.log.info("%s failed to load!" % (plug))
elif command == "help":
self.log.info("/reload - reload plugins")
self.log.info("/plugins - lists plugins")
self.log.info("/update-wrapper - Checks for new updates, and will install them automatically if one is available")
self.log.info("/start & /stop - start and stop the server without auto-restarting respectively without shutting down Wrapper.py")
self.log.info("/restart - restarts the server, obviously")
self.log.info("/halt - shutdown Wrapper.py completely")
self.log.info("Wrapper.py Version %s" % self.getBuildString())
else:
self.log.error("Invalid command %s" % command)
示例14: BaskitCLI
# 需要导入模块: from server import Server [as 别名]
# 或者: from server.Server import stop [as 别名]
class BaskitCLI(cmd.Cmd):
prompt = 'baskit> '
server = None
def __init__(self):
cmd.Cmd.__init__(self)
self.server = Server()
# This is some initialization stuff to make sure that the directory
# structure that baskit expects is in place.
for item in [self.server.env,
os.path.join(self.server.env, 'archive', 'backups'),
os.path.join(self.server.env, 'archive', 'snaps'),
os.path.join(self.server.env, 'persistent'),
os.path.join(self.server.env, 'env')]:
if not os.path.exists(item):
os.makedirs(item)
def do_help(self, s):
if s == '': self.onecmd('help help')
else:
cmd.Cmd.do_help(self, s)
def help_help(self):
print '''Welcome to the Baskit Minecraft Server Manager!
Baskit is designed to be a minimalistic, yet powerful server management
system. Baskit uses GNU-Screen at the heart of the application and
simply wrap around that. This means that you can perform in-place
upgrades of Baskit, or even remove it completely without worry of it
impacting the running server. There are a lot of functions available to
help assist you in managing the server as well, below is a high-level
list of what is available. For further detail (including avalable
options) for any command, type help [COMMAND].
start Starts the server.
stop Stops the server.
restart Restarts the server.
server Returns the running state & server binary
information that we have on-hand about
the running server.
cmd [COMMAND] Sends the command specified to the server.
There is no limit as to what can be sent
here, and it is quite easy to script
commands into the server with this.
players Returns the list of players currently logged
into the server.
console Will drop you directly into the server
console. From here you are directly
interacting with the server. To detach from
the server console, hit CNTRL+A,D to exit.
update Allows you to update the server binary based
on the conditions you had specified. It's
highly recommended you run help update to
get some more detail.
backup All backup related functions are housed
within the backup command. Running "backup"
will present it's help.
snapshot All snapshot related functions are housed
within the snapshot command. Running
"snapshot" will present it's help.
sync Handles syncing to/from ramdisk and
persistent storage if ramdisk support is
enabled (disabled by default)
'''
def do_exit(self, s):
'''exit
Exits the interactive CLI
'''
return True
def do_cmd(self, s):
'''cmd [COMMAND]
Sends the specified command to the Minecraft server console
'''
self.server.command(s)
print 'Sent to console: %s' % s
def do_players(self, s):
'''players
Retuns a list of the currently connected players
'''
if not self.server.running():
#.........这里部分代码省略.........
示例15: RefMon
# 需要导入模块: from server import Server [as 别名]
# 或者: from server.Server import stop [as 别名]
class RefMon(app_manager.RyuApp):
OFP_VERSIONS = [ofproto_v1_0.OFP_VERSION, ofproto_v1_3.OFP_VERSION]
_CONTEXTS = { 'wsgi': WSGIApplication }
def __init__(self, *args, **kwargs):
super(RefMon, self).__init__(*args, **kwargs)
# Use REST API for Anomaly Detection for now
wsgi = kwargs['wsgi']
wsgi.register(AnomalyDetectionReceiver, self)
self.logger = util.log.getLogger('ReferenceMonitor')
self.logger.info('refmon: start')
# retrieve command line arguments
CONF = cfg.CONF
log_file_path = CONF['refmon']['log']
if log_file_path is not None:
log_file = os.path.abspath(log_file_path)
self.log = open(log_file, "w")
else:
self.log = None
# configure flow mod logging
log_file_path = CONF['refmon']['flowmodlog']
if log_file_path is not None:
log_file = os.path.abspath(log_file_path)
self.flow_mod_log = open(log_file, "w")
else:
self.flow_mod_log = None
# load config from file
self.logger.info('refmon: load config')
try:
config_file_path = CONF['refmon']['config']
config_file = os.path.abspath(config_file_path)
self.config = Config(config_file)
except InvalidConfigError as e:
self.logger.info('refmon: invalid config '+str(e))
# No sense to continue the execution
sys.exit()
self.config.always_ready = CONF['refmon']['always_ready']
# start controller
if self.config.isMultiSwitchMode():
self.controller = MultiSwitchController(self.config)
elif self.config.isMultiTableMode():
self.controller = MultiTableController(self.config)
elif self.config.isMultiHopMode():
self.controller = MultiHopController(self.config)
# this must be set before Server, which uses it.
self.flow_mod_times = Queue()
# start server receiving flowmod requests
self.server = Server(self, self.config.server["IP"], self.config.server["Port"], self.config.server["key"])
self.server.start()
def close(self):
self.logger.info('refmon: stop')
if self.log:
self.log.close()
if self.flow_mod_log:
self.flow_mod_log.close()
self.server.stop()
@set_ev_cls(ofp_event.EventOFPStateChange, [MAIN_DISPATCHER, DEAD_DISPATCHER])
def dp_state_change_handler(self, ev):
datapath = ev.datapath
if ev.state == MAIN_DISPATCHER:
self.controller.switch_connect(datapath)
elif ev.state == DEAD_DISPATCHER:
self.controller.switch_disconnect(datapath)
@set_ev_cls(ofp_event.EventOFPPacketIn, MAIN_DISPATCHER)
def _packet_in_handler(self, ev):
self.controller.packet_in(ev)
@set_ev_cls(ofp_event.EventOFPBarrierReply, MAIN_DISPATCHER)
def barrier_reply_handler(self, ev):
datapath = ev.msg.datapath
if self.controller.handle_barrier_reply(datapath):
end_time = time()
try:
start_time = self.flow_mod_times.get_nowait()
except Empty:
pass
if self.log:
self.log.write(str(start_time) + " " + str(end_time) + " " + str(end_time - start_time) + "\n")
def process_flow_mods(self, msg):
self.flow_mod_times.put(time())
#.........这里部分代码省略.........