Search Results

Search found 24 results on 1 pages for 'keyboardinterrupt'.

Page 1/1 | 1 

  • Why can't I handle a KeyboardInterrupt in python?

    - by Josh
    I'm writing python 2.6.6 code on windows that looks like this: try: dostuff() except KeyboardInterrupt: print "Interrupted!" except: print "Some other exception?" finally: print "cleaning up...." print "done." dostuff() is a function that loops forever, reading a line at a time from an input stream and acting on it. I want to be able to stop it and clean up when I hit ctrl-c. What's happening instead is that the code under except KeyboardInterrupt: isn't running at all. The only thing that gets printed is "cleaning up...", and then a traceback is printed that looks like this: Traceback (most recent call last): File "filename.py", line 119, in <module> print 'cleaning up...' KeyboardInterrupt So, exception handling code is NOT running, and the traceback claims that a KeyboardInterrupt occurred during the finally clause, which doesn't make sense because hitting ctrl-c is what caused that part to run in the first place! Even the generic except: clause isn't running. EDIT: Based on the comments, I replaced the contents of the try: block with sys.stdin.read(). The problem still occurs exactly as described, with the first line of the finally: block running and then printing the same traceback.

    Read the article

  • Catching KeyboardInterrupt when working with PyGame

    - by Sebastian P.
    I have written a small Python application where I use PyGame for displaying some simple graphics. I have a somewhat simple PyGame loop going in the base of my application, like so: stopEvent = Event() # Just imagine that this eventually sets the stopEvent # as soon as the program is finished with its task. disp = SortDisplay(algorithm, stopEvent) def update(): """ Update loop; updates the screen every few seconds. """ while True: stopEvent.wait(options.delay) disp.update() if stopEvent.isSet(): break disp.step() t = Thread(target=update) t.start() while not stopEvent.isSet(): for event in pygame.event.get(): if event.type == pygame.QUIT: stopEvent.set() It works all fine and dandy for the normal program termination; if the PyGame window gets closed, the application closes; if the application finishes its task, the application closes. The trouble I'm having is, if I Ctrl-C in the Python console, the application throws a KeyboardInterrupt, but keeps on running. The question would therefore be: What have I done wrong in my update loop, and how do I rectify it so a KeyboardInterrupt causes the application to terminate?

    Read the article

  • Avoiding accidentally catching KeyboardInterrupt and SystemExit in Python 2.4

    - by jrdioko
    In Python scripts, there are many cases where a keyboard interrupt (Ctrl-C) fails to kill the process because of a bare except clause somewhere in the code: try: foo() except: bar() The standard solution in Python 2.5 or higher is to catch Exception rather than using bare except clauses: try: foo() except Exception: bar() This works because, as of Python 2.5, KeyboardInterrupt and SystemExit inherit from BaseException, not Exception. However, some installations are still running Python 2.4. How can this problem be handled in versions prior to Python 2.5? (I'm going to answer this question myself, but putting it here so people searching for it can find a solution.)

    Read the article

  • Play mp3 using Python, PyQt, and Phonon

    - by KeyboardInterrupt
    I been trying all day to figure out the Qt's Phonon library with Python. My long term goal is to see if I could get it to play a mms:// stream, but since I can't find an implementation of this done anywhere, I will figure that part out myself. (figured I'd put it out there if anyone knew more about this specifically, if not no big deal.) Anyway, I figured I'd work backwards from a working example I found online. This launches a file browser and will play the mp3 file specified. I wanted to strip out the file browser stuff and get it down to the essentials of executing the script and having it play an Mp3 file with a hardcoded path. I'm assuming my problem is a misunderstanding of setCurrentSource() and specifying the data types. (see: http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/phonon-mediasource.html#fileName) I'm keeping my question kind of broad because ANY help with understanding Phonon would be greatly appreciated. import sys from PyQt4.QtGui import QApplication, QMainWindow, QDirModel, QColumnView from PyQt4.QtGui import QFrame from PyQt4.QtCore import SIGNAL from PyQt4.phonon import Phonon class MainWindow(QMainWindow): m_model = QDirModel() def __init__(self): QMainWindow.__init__(self) self.m_fileView = QColumnView(self) self.m_media = None self.setCentralWidget(self.m_fileView) self.m_fileView.setModel(self.m_model) self.m_fileView.setFrameStyle(QFrame.NoFrame) self.connect(self.m_fileView, SIGNAL("updatePreviewWidget(const QModelIndex &)"), self.play) def play(self, index): self.delayedInit() self.m_media.setCurrentSource( Phonon.MediaSource(self.m_model.filePath(index))) self.m_media.play() def delayedInit(self): if not self.m_media: self.m_media = Phonon.MediaObject(self) audioOutput = Phonon.AudioOutput(Phonon.MusicCategory, self) Phonon.createPath(self.m_media, audioOutput) def main(): app = QApplication(sys.argv) QApplication.setApplicationName("Phonon Tutorial 2 (Python)") mw = MainWindow() mw.show() sys.exit(app.exec_()) if __name__ == '__main__': main()

    Read the article

  • Use Django ORM as standalone [closed]

    - by KeyboardInterrupt
    Possible Duplicates: Use only some parts of Django? Using only the DB part of Django I want to use the Django ORM as standalone. Despite an hour of searching Google, I'm still left with several questions: Does it require me to set up my Python project with a setting.py, /myApp/ directory, and modules.py file? Can I create a new models.py and run syncdb to have it automatically setup the tables and relationships or can I only use models from existing Django projects? There seems to be a lot of questions regarding PYTHONPATH. If you're not calling existing models is this needed? I guess the easiest thing would be for someone to just post a basic template or walkthrough of the process, clarifying the organization of the files e.g.: db/ __init__.py settings.py myScript.py orm/ __init__.py models.py And the basic essentials: # settings.py from django.conf import settings settings.configure( DATABASE_ENGINE = "postgresql_psycopg2", DATABASE_HOST = "localhost", DATABASE_NAME = "dbName", DATABASE_USER = "user", DATABASE_PASSWORD = "pass", DATABASE_PORT = "5432" ) # orm/models.py # ... # myScript.py # import models.. And whether you need to run something like: django-admin.py inspectdb ... (Oh, I'm running Windows if that changes anything regarding command-line arguments.).

    Read the article

  • python: can't terminate a thread hung in socket.recvfrom() call

    - by Dihlofos
    Hello, everyone I cannot get a way to terminate a thread that is hung in a socket.recvfrom() call. For example, ctrl+c that should trigger KeyboardInterrupt exception can't be caught. Here is a script I've used for testing: from socket import * from threading import Thread from sys import exit class TestThread(Thread): def __init__(self,host="localhost",port=9999): self.sock = socket(AF_INET,SOCK_DGRAM) self.sock.bind((host,port)) super(TestThread,self).__init__() def run(self): while True: try: recv_data,addr = self.sock.recvfrom(1024) except (KeyboardInterrupt, SystemExit): sys.exit() if __name__ == "__main__": server_thread = TestThread() server_thread.start() while True: pass The main thread (the one that executes infinite loop) exits. However the thread that I explicitly create, keeps hanging in recvfrom(). Please, help me resolve this.

    Read the article

  • Spikes in Socket Performance

    - by Harun Prasad
    We are facing random spikes in high throughput transaction processing system using sockets for IPC. Below is the setup used for the run: The client opens and closes new connection for every transaction, and there are 4 exchanges between the server and the client. We have disabled the TIME_WAIT, by setting the socket linger (SO_LINGER) option via getsockopt as we thought that the spikes were caused due to the sockets waiting in TIME_WAIT. There is no processing done for the transaction. Only messages are passed. OS used Centos 5.4 The average round trip time is around 3 milli seconds, but some times the round trip time ranges from 100 milli seconds to couple of seconds. Steps used for Execution and Measurement and output Starting the server $ python sockServerLinger.py /dev/null & Starting the client to post 1 million transactions to the server. And logs the time for a transaction in the client.log file. $ python sockClient.py 1000000 client.log Once the execution finishes the following command will show the execution time greater than 100 milliseconds in the format <line_number>:<execution_time>. $ grep -n "0.[1-9]" client.log | less Below is the example code for Server and Client. Server # File: sockServerLinger.py import socket, traceback,time import struct host = '' port = 9999 l_onoff = 1 l_linger = 0 lingeropt = struct.pack('ii', l_onoff, l_linger) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, lingeropt) s.bind((host, port)) s.listen(1) while 1: try: clientsock, clientaddr = s.accept() print "Got connection from", clientsock.getpeername() data = clientsock.recv(1024*1024*10) #print "asdasd",data numsent=clientsock.send(data) data1 = clientsock.recv(1024*1024*10) numsent=clientsock.send(data) ret = 1 while(ret>0): data1 = clientsock.recv(1024*1024*10) ret = len(data) clientsock.close() except KeyboardInterrupt: raise except: print traceback.print_exc() continue Client # File: sockClient.py import socket, traceback,sys import time i = 0 while 1: try: st = time.time() s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) while (s.connect_ex(('127.0.0.1',9999)) != 0): continue numsent=s.send("asd"*1000) response = s.recv(6000) numsent=s.send("asd"*1000) response = s.recv(6000) i+=1 if i == int(sys.argv[1]): break except KeyboardInterrupt: raise except: print "in exec:::::::::::::",traceback.print_exc() continue print time.time() -st

    Read the article

  • Indicator-cpufreq does not work at 12.04 ¿infinite loop insaid?

    - by Juan
    Good night, i want to use indicator-cpufreq, but it is not possible, i think that when i start it, i get an infinite loop and it doesnt start I think i am doing it well, here you have a snapshoot when i try to start it http://i.stack.imgur.com/mvaYf.jpg But 6 or 7 minutes later, it continues at the same point, i have to stop it with Ctrl-c, and shows that: http://i.stack.imgur.com/Vi0pp.jpg It says:" Traceback (most recent call last): File "/usr/bin/indicator-cpufreq", line 82, in gtk.main() KeyboardInterrupt" I do not have idea of what do for fix that, i hope you can help me to do that Thanks for your time and sorry about my english

    Read the article

  • BasicHTTPServer, SimpleHTTPServer and concurrency

    - by braindump
    I'm writing a small web server for testing purposes using python, BasicHTTPServer and SimpleHTTPServer. It looks like it's processing one request at a time. Is there any way to make it a little faster without messing around too deeply? Basicly my code looks as the following and I'd like to keep it this simple ;) os.chdir(webroot) httpd = BaseHTTPServer.HTTPServer(("", port), SimpleHTTPServer.SimpleHTTPRequestHandler) print("Serving directory %s on port %i" %(webroot, port) ) try: httpd.serve_forever() except KeyboardInterrupt: print("Server stopped.")

    Read the article

  • Python + PyQt program freezes

    - by DSblizzard
    I wrote PyQt application. After it's start I close it (GUI), but timer don't stops and Python sometimes freezes. Only thing to unfreeze it - Ctrl-C, after which following message appears: Traceback (most recent call last): File "", line 262, in timerEvent KeyboardInterrupt timer don't stops again, and CPython works very slowly. How to avoid this problem?

    Read the article

  • MPI signal handling

    - by Seth Johnson
    When using mpirun, is it possible to catch signals (for example, the SIGINT generated by ^C) in the code being run? For example, I'm running a parallelized python code. I can except KeyboardInterrupt to catch those errors when running python blah.py by itself, but I can't when doing mpirun -np 1 python blah.py. Does anyone have a suggestion? Even finding how to catch signals in a C or C++ compiled program would be a helpful start. If I send a signal to the spawned Python processes, they can handle the signals properly; however, signals sent to the parent orterun process (i.e. from exceeding wall time on a cluster, or pressing control-C in a terminal) will kill everything immediately.

    Read the article

  • Launching python within python and timezone issue

    - by Gabi Purcaru
    I had to make a launcher script for my django app, and it seems it somehow switches the timezone to GMT (default being +2), and every datetime is two hours behind when using the script. What could be causing that? Here is the launcher script that I use: #!/usr/bin/env python import os import subprocess import shlex import time cwd = os.getcwd() p1 = subprocess.Popen(shlex.split("python manage.py runserver"), cwd=os.path.join(cwd, "drugsworld")) p2 = subprocess.Popen(shlex.split("python coffee_auto_compiler.py"), cwd=os.path.join(cwd)) try: while True: time.sleep(2) except KeyboardInterrupt: p1.terminate() p2.terminate() If I manually run python manage.py runserver, the timezone is +2. If, however, I use this script, the timezone is set to GMT.

    Read the article

  • Python GUI Scraper hanging issues.

    - by bball
    I wrote a scraper using python a while back, and it worked fine in the command line. I have made a GUI for the application now, but I am having trouble with one issue. When I attempt to update text inside the gui (e.g. 'fetching URL 12/50'), I am unable seeing as the function within the scraper is grabbing 100+ links. Also when going from one scraping function, to a function that should update the gui, to another function, the gui update function seems to be skipped over while the next scrape function is run. An example would be: scrapeLinksA() #takes 20 seconds updateInfo("LinksA done") scrapeLinksB() #takes another 20 seconds in the above example, updateInfo is never executed, unless I end the program with a KeyboardInterrupt. I'm thinking my solution is threading, but I'm not sure. What can I do to fix this? I am using: PyQt4 urllib2 BeautifulSoup

    Read the article

  • How to make socket.listen(1) work for some time and then continue rest of code???

    - by Rami Jarrar
    I'm making server that make a tcp socket and work over port range, with each port it will listen on that port for some time, then continue the rest of the code. like this:: import socket sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sck.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) msg ='' ports = [x for x in xrange(4000)] while True: try: for i in ports: sck.bind(('',i)) ## sck.listen(1) ## make it just for some time and then continue this ## if there a connection do this conn, addr = sck.accept() msg = conn.recv(2048) ## do something ##if no connection continue the for loop conn.close() except KeyboardInterrupt: exit() so how i could make sck.listen(1) work just for some time ??

    Read the article

  • Python - Subprocess Popen and Thread error

    - by n0idea
    In both functions record and ftp, i have subprocess.Popen if __name__ == '__main__': try: t1 = threading.Thread(target = record) t1.daemon = True t1.start() t2 = threading.Thread(target = ftp) t2.daemon = True t2.start() except (KeyboardInterrupt, SystemExit): sys.exit() The error I'm receiving is: Exception in thread Thread-1 (most likely raised during interpreter shutdown): Traceback (most recent call last): File "/usr/lib/python2.7/threading.py", line 551, in __bootstrap_inner File "/usr/lib/python2.7/threading.py", line 504, in run File "./in.py", line 20, in recordaudio File "/usr/lib/python2.7/subprocess.py", line 493, in call File "/usr/lib/python2.7/subprocess.py", line 679, in __init__ File "/usr/lib/python2.7/subprocess.py", line 1237, in _execute_child <type 'exceptions.AttributeError'>: 'NoneType' object has no attribute 'close' What might the issue be ?

    Read the article

  • stuck in while loop python

    - by user1717330
    I am creating a chat server in python and got quite far as a noob in the language. I am having 1 problem at the moment which I want to solve before I go further, but I cannot seem to find how to get the problem solved. It is about a while loop that continues.. in the below code is where it goes wrong while 1: try: data = self.channel.recv ( 1024 ) print "Message from client: ", data if "exit" in data: self.channel.send("You have closed youre connection.\n") break except KeyboardInterrupt: break except: raise When this piece of code get executed, on my client I need to enter "exit" to quit the connection. This works as a charm, but when I use CTRL+C to exit the connection, my server prints "Message from client: " a couple of thousand times. where am I going wrong?

    Read the article

  • Interrupting `while loop` with keyboard in Cython

    - by linello
    I want to be able to interrupt a long function with cython, using the usual CTRL+C interrupt command. My C++ long function is repeatedly called inside a while loop from Cython code, but I want to be able, during the loop, to send an "interrupt" and block the while loop. The interrupt also should wait the longFunction() to finish, so that no data are lost or kept in unknown status. This is one of my first implementation, which obviously doesn't work: computed=0; print "Computing long function..." while ( computed==0 ): try: computed = self.thisptr.aLongFunction() except (KeyboardInterrupt, SystemExit): computed=1 print '\n! Received keyboard interrupt.\n' break; (p.s. self.thisptr is the pointer to the current class which implements aLongFunction() )

    Read the article

  • Problems with sys.stdout.write() with time.sleep() in a function

    - by philipjkim
    What I wanted is printing out 5 dots that a dot printed per a second using time.sleep(), but the result was 5 dots were printed at once after 5 seconds delay. Tried both print and sys.stdout.write, same result. Thanks for any advices. import time import sys def wait_for(n): """Wait for {n} seconds. {n} should be an integer greater than 0.""" if not isinstance(n, int): print 'n in wait_for(n) should be an integer.' return elif n < 1: print 'n in wait_for(n) should be greater than 0.' return for i in range(0, n): sys.stdout.write('.') time.sleep(1) sys.stdout.write('\n') def main(): wait_for(5) # FIXME: doesn't work as expected if __name__ == '__main__': try: main() except KeyboardInterrupt: print '\nAborted.'

    Read the article

  • Starting a process in one HTTP call and getting results in another

    - by KillianDS
    Hi, I'm writing a very simple testing framework for my application, the design isn't perfect, but I don't have time to write something more complex. Essentially, I have a client and server-application, on my server I want a small python web server to start the server application with given test sequences on a GET or POST call. Also, the application prints some testdata to stderr which I'd like to catch and return in another HTTP call. At the moment I have this: from subprocess import Popen, PIPE from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer p = None class MyHandler(BaseHTTPRequestHandler): def do_GET(self): global p if self.path.endswith("start/"): p = Popen(["./bin/Release/simplex264","BBB-360","127.0.0.1"], stderr=PIPE) print 'started' return elif self.path.endswith("getResults/"): self.wfile.write(p.stderr.read()) return self.send_error(404,'File Not Found: %s' % self.path) def main(): try: server = HTTPServer(('localhost', 9876), MyHandler) print 'Started server...' server.serve_forever() except KeyboardInterrupt: print 'Shutting down...' server.socket.close() if __name__ == '__main__': main() Which 'works', except for one part, when I try to open http://localhost:9876/start/, it does not return before the process ended. However, the 'started' appears in my shell immediately (I added this because I thought the Popen call would only return after execution). I do not know the perfect inner workings of Popen and BaseHTTPRequestHandler however and do not really know where it goes wrong. Is there any way to make this work asynchronously?

    Read the article

  • Slow Python HTTP server on localhost

    - by Abiel
    I am experiencing some performance problems when creating a very simple Python HTTP server. The key issue is that performance is varying depending on which client I use to access it, where the server and all clients are being run on the local machine. For instance, a GET request issued from a Python script (urllib2.urlopen('http://localhost/').read()) takes just over a second to complete, which seems slow considering that the server is under no load. Running the GET request from Excel using MSXML2.ServerXMLHTTP also feels slow. However, requesting the data Google Chrome or from RCurl, the curl add-in for R, yields an essentially instantaneous response, which is what I would expect. Adding further to my confusion is that I do not experience any performance problems for any client when I am on my computer at work (the performance problems are on my home computer). Both systems run Python 2.6, although the work computer runs Windows XP instead of 7. Below is my very simple server example, which simply returns 'Hello world' for any get request. from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer class MyHandler(BaseHTTPRequestHandler): def do_GET(self): print("Just received a GET request") self.send_response(200) self.send_header("Content-type", "text/html") self.end_headers() self.wfile.write('Hello world') return def log_request(self, code=None, size=None): print('Request') def log_message(self, format, *args): print('Message') if __name__ == "__main__": try: server = HTTPServer(('localhost', 80), MyHandler) print('Started http server') server.serve_forever() except KeyboardInterrupt: print('^C received, shutting down server') server.socket.close() Note that in MyHandler I override the log_request() and log_message() functions. The reason is that I read that a fully-qualified domain name lookup performed by one of these functions might be a reason for a slow server. Unfortunately setting them to just print a static message did not solve my problem. Also, notice that I have put in a print() statement as the first line of the do_GET() routine in MyHandler. The slowness occurs prior to this message being printed, meaning that none of the stuff that comes after it is causing a delay.

    Read the article

  • What could cause xmlrpclib.ResponseError: ResponseError() ?

    - by Tom
    Hi, I am experimenting with XML-RPC. I have the following server script (python): from SimpleXMLRPCServer import SimpleXMLRPCServer server = SimpleXMLRPCServer(('localhost', 9000)) def return_input(someinput): return someinput server.register_function(return_input) try: print 'ctrl-c to stop server' server.serve_forever() except KeyboardInterrupt: print 'stopping' and the following client script: import xmlrpclib server = xmlrpclib.ServerProxy('http://www.example.com/pathto/xmlrpcTester2.py') print server.return_input('some input') I have tested this locally and it works fine. All it does it spit out the input fron the client script, which is right. However, when I try to do it on a remote server I get the following error: Traceback (most recent call last): File "client.py", line 4, in <module> print server.return_input('some input') File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/xmlrpclib.py", line 1199, in __call__ return self.__send(self.__name, args) File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/xmlrpclib.py", line 1489, in __request verbose=self.__verbose File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/xmlrpclib.py", line 1253, in request return self._parse_response(h.getfile(), sock) File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/xmlrpclib.py", line 1392, in _parse_response return u.close() File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/xmlrpclib.py", line 836, in close raise ResponseError() xmlrpclib.ResponseError: ResponseError() Any ideas what could cause this? Thanks in advance for your help.

    Read the article

  • Python 3.3 Webserver restarting problems

    - by IPDGino
    I have made a simple webserver in python, and had some problems with it before as described here: Python (3.3) Webserver script with an interesting error In that question, the answer was to use a While True: loop so that any crashes or errors would be resolved instantly, because it would just start itself again. I've used this for a while, and still want to make the server restart itself every few minutes, but on Linux for some reason it won't work for me. On windows the code below works fine, but on linux it keeps saying Handler class up here ... ... class Server: def __init__(self): self.server_class = HTTPServer self.server_adress = ('MY IP GOES HERE, or localhost', 8080) global httpd httpd = self.server_class(self.server_adress, Handler) self.main() def main(self): if count > 1: global SERVER_UP_SINCE HOUR_CHECK = int(((count - 1) * RESTART_INTERVAL) / 60) SERVER_UPTIME = str(HOUR_CHECK) + " MINUTES" if HOUR_CHECK > 60: minutes = int(HOUR_CHECK % 60) hours = int(HOUR_CHECK // 60) SERVER_UPTIME = ("%s HOURS, %s MINUTES" % (str(hours), str(minutes))) SERVING_ON_ADDR = self.server_adress SERVER_UP_SINCE = str(SERVER_UP_SINCE) SERVER_RESTART_NUMBER = count - 1 print(""" SERVER INFO ------------------------------------- SERVER_UPTIME: %s SERVER_UP_SINCE: %s TOTAL_FILES_SERVED: %d SERVING_ON_ADDR: %s SERVER_RESTART_NUMBER: %s \n\nSERVER HAS RESTARTED """ % (SERVER_UPTIME, SERVER_UP_SINCE, TOTAL_FILES, SERVING_ON_ADDR, SERVER_RESTART_NUMBER)) else: print("SERVER_BOOT=1\nSERVER_ONLINE=TRUE\nRESTART_LOOP=TRUE\nSERVING_ON_ADDR:%s" % str(self.server_adress)) while True: try: httpd.serve_forever() except KeyboardInterrupt: print("Shutting down...") break httpd.shutdown() httpd.socket.close() raise(SystemExit) return def server_restart(): """If you want the restart timer to be longer, replace the number after the RESTART_INTERVAL variable""" global RESTART_INTERVAL RESTART_INTERVAL = 10 threading.Timer(RESTART_INTERVAL, server_restart).start() global count count = count + 1 instance = Server() if __name__ == "__main__": global SERVER_UP_SINCE SERVER_UP_SINCE = strftime("%d-%m-%Y %H:%M:%S", gmtime()) server_restart() Basically, I make a thread to restart it every 10 seconds (For testing purposes) and start the server. After ten seconds it will say File "/home/username/Desktop/Webserver/server.py", line 199, in __init__ httpd = self.server_class(self.server_adress, Handler) File "/usr/lib/python3.3/socketserver.py", line 430, in __init__ self.server_bind() File "/usr/lib/python3.3/http/server.py", line 135, in server_bind socketserver.TCPServer.server_bind(self) File "/usr/lib/python3.3/socketserver.py", line 441, in server_bind self.socket.bind(self.server_address) OSError: [Errno 98] Address already in use As you can see in the except KeyboardInterruption line, I tried everything to make the server stop, and the program stop, but it will NOT stop. But the thing I really want to know is how to make this server able to restart, without giving some wonky errors.

    Read the article

  • CherryPy sessions for same domain, different port

    - by detly
    Consider the script below. It will launch two subprocesses, each one a CherryPy app (hit Ctrl+C or whatever the KeyboardInterrupt combo is on your system to end them both). If you run it with CP 3.0 (taking care to change the 3.0/3.1 specific lines in "StartServer"), then visit: http://localhost:15002/ ...you see an empty dict. Then visit: http://localhost:15002/set?val=10 http://localhost:15002/ ...and you see the newly populated dict. Then visit: http://localhost:15012/ ...and go back to http://localhost:15002/ ...and nothing has changed. If you try the same thing with CP 3.1 (remember the lines in "StartServer"!), when you get to the last step, the dict is now empty. This happens in Windows and Debian, Python 2.5 and 2.6. You can try all sorts of things: changing to file storage, separating the storage paths... the only difference it makes is that the sessions might get merged instead of erased. I've read another post about this as well, and there's a suggestion there to put the session tools config keys in the app config rather than the global config, but I don't think that's relevant to this usage where the apps run independently. What do I do to get independent CherryPy applications to NOT interfere with each other? Note: I originally asked this on the CherryPy mailing list but haven't had a response yet so I'm trying here. I hope that's okay. import os, os.path, socket, sys import subprocess import cgi import cherrypy HTTP_PORT = 15002 HTTP_HOST = "127.0.0.1" site1conf = { 'global' : { 'server.socket_host' : HTTP_HOST, 'server.socket_port' : HTTP_PORT, 'tools.sessions.on' : True, # 'tools.sessions.storage_type': 'file', # 'tools.sessions.storage_path': '1', # 'tools.sessions.storage_path': '.', 'tools.sessions.timeout' : 1440}} site2conf = { 'global' : { 'server.socket_host' : HTTP_HOST, 'server.socket_port' : HTTP_PORT + 10, 'tools.sessions.on' : True, # 'tools.sessions.storage_type': 'file', # 'tools.sessions.storage_path': '2', # 'tools.sessions.storage_path': '.', 'tools.sessions.timeout' : 1440}} class Home(object) : def __init__(self, key): self.key = key @cherrypy.expose def index(self): return """\ <html> <body>Session: <br>%s </body> </html> """ % cgi.escape(str(dict(cherrypy.session))) @cherrypy.expose def set(self, val): cherrypy.session[self.key.upper()] = val return """\ <html> <body>Set %s to %s</body> </html>""" % (cgi.escape(self.key), cgi.escape(val)) def StartServer(conf, key): cherrypy.config.update(conf) print 'Starting server (%s)' % key cherrypy.tree.mount(Home(key), '/', {}) # Start the web server. #### 3.0 # cherrypy.server.quickstart() # cherrypy.engine.start() #### #### 3.1 cherrypy.engine.start() cherrypy.engine.block() #### def Main(): # Start first webserver proc1 = subprocess.Popen( [sys.executable, os.path.abspath(__file__), "1"]) proc2 = subprocess.Popen( [sys.executable, os.path.abspath(__file__), "2"]) proc1.wait() proc2.wait() if __name__ == "__main__": print sys.argv if len(sys.argv) == 1: # Master process Main() elif(int(sys.argv[1]) == 1): StartServer(site1conf, 'magic') elif(int(sys.argv[1]) == 2): StartServer(site2conf, 'science') else: sys.exit(1)

    Read the article

  • Mercurial over ssh client and server on Windows

    - by Ben Von Handorf
    I'm trying to configure Mercurial for use with both a windows server (freeSSHd) and client (both command line and TortoiseHG). I'm using the most recent versions of everything... all downloaded in the past few days. Using public key auth, I have been able to get connected to the server and I'm able to use plink to execute "hg version" and get a response, but when I try to clone a repository from the ssh server the command appears to hang. Running with -v yields: hg -v clone ssh://<username>@<server>//hg/repositoryA testRepositoryA running "plink.exe -i "<path to private key file>" <username>@<server> "hg -R /hg/repositoryA serve --stdio"" with nothing more forthcoming. Running the hg serve command directly on the server yields an apparently responsive Mercurial server, but the clients do not seem to make any further requests. Running "hg serve" in the repository directory and cloning over http works perfectly. What should I be looking for to help debug this? Is there something the clients (hg and TortoiseHG) aren't sending to continue the request stream? Additional Information: If I change to an invalid repository on the target machine, the appropriate error is displayed, so it does appear that the remote hg is running and correctly evaluating the path. Running with --debug and --traceback results in: sending hello command sending between command It hangs here, until I CTRL-C Traceback (most recent call last): File "mercurial\dispatch.pyo", line 46, in _runcatch File "mercurial\dispatch.pyo", line 452, in _dispatch File "mercurial\dispatch.pyo", line 320, in runcommand File "mercurial\dispatch.pyo", line 504, in _runcommand File "mercurial\dispatch.pyo", line 457, in checkargs File "mercurial\dispatch.pyo", line 451, in <lambda> File "mercurial\util.pyo", line 402, in check File "mercurial\commands.pyo", line 636, in clone File "mercurial\hg.pyo", line 187, in clone File "mercurial\hg.pyo", line 63, in repository File "mercurial\sshrepo.pyo", line 51, in __init__ File "mercurial\sshrepo.pyo", line 73, in validate_repo KeyboardInterrupt interrupted! Responding to Ryan: There does not appear to be any CPU usage or increasing memory usage on the server. It appears to be waiting for the client to send a request or something similar. 11/19/2009 : More information: The problem is definitely in the freeSSHd/server side of the equation. Connecting to bitbucket over ssh with the same keyset works fine. Still working on this.

    Read the article

1