How to handle KeyboardInterrupt (Ctrl-c) nicely with pycurl? How to handle KeyboardInterrupt (Ctrl-c) nicely with pycurl? curl curl

How to handle KeyboardInterrupt (Ctrl-c) nicely with pycurl?


You need to catch CTRL+C and process that signal
Original: Example 1
Original: Example 2


Example 1

#!/usr/bin/env pythonimport signalimport sysdef signal_handler(signal, frame):        print 'You pressed Ctrl+C!'        sys.exit(0)signal.signal(signal.SIGINT, signal_handler)print 'Press Ctrl+C'signal.pause()

Example 2

import signal, osdef handler(signum, frame):    print 'Signal handler called with signal', signum    raise IOError("Couldn't open device!")# Set the signal handler and a 5-second alarmsignal.signal(signal.SIGALRM, handler)signal.alarm(5)# This open() may hang indefinitelyfd = os.open('/dev/ttyS0', os.O_RDWR)signal.alarm(0)          # Disable the alarm

And at least something is not working on that twitter link, see here

  • don't forget to put conn.close() after conn.perform()

And it's helpfull to have debug mode enabled when testing.

import pycurlusername = 'your_user_name'password = 'your_password'def body(buf):    for item in buf.strip().split('\n'):        if item.strip():            print itemdef test(debug_type, debug_msg):    if len(debug_msg) < 300:        print "debug(%d): %s" % (debug_type, debug_msg.strip())conn = pycurl.Curl()  conn.setopt(pycurl.USERNAME, username)conn.setopt(pycurl.PASSWORD, password)#conn.setopt(pycurl.SSL_VERIFYPEER, False)conn.setopt(pycurl.FOLLOWLOCATION, True)conn.setopt(pycurl.VERBOSE, True)conn.setopt(pycurl.URL, 'https://stream.twitter.com/1.1/statuses/sample.json')  conn.setopt(pycurl.DEBUGFUNCTION, test)conn.setopt(pycurl.WRITEFUNCTION, body)conn.perform()conn.close()

Just copy/paste working test Example

➜  ~  hcat twitter.py import pycurlimport signalimport sysfrom time import sleepusername = 'bubudee'password = 'deebubu'def body(buf):    for item in buf.strip().split('\n'):        if item.strip():            print itemdef test(debug_type, debug_msg):    if len(debug_msg) < 300:        print "debug(%d): %s" % (debug_type, debug_msg.strip())def handle_ctrl_c(signal, frame):    print "Got ctrl+c, going down!"    sys.exit(0)signal.signal(signal.SIGINT, handle_ctrl_c)conn = pycurl.Curl()  conn.setopt(pycurl.USERNAME, username)conn.setopt(pycurl.PASSWORD, password)#conn.setopt(pycurl.SSL_VERIFYPEER, False)conn.setopt(pycurl.FOLLOWLOCATION, True)conn.setopt(pycurl.VERBOSE, True)conn.setopt(pycurl.URL, 'https://stream.twitter.com/1.1/statuses/sample.json')  conn.setopt(pycurl.DEBUGFUNCTION, test)conn.setopt(pycurl.WRITEFUNCTION, body)conn.perform()print "Who let the dogs out?:p"sleep(10)conn.close()➜  ~  python twitter.py debug(0): About to connect() to stream.twitter.com port 443 (#0)debug(0): Trying 199.16.156.110...debug(0): Connected to stream.twitter.com (199.16.156.110) port 443 (#0)debug(0): Initializing NSS with certpath: sql:/etc/pki/nssdbdebug(0): CAfile: /etc/pki/tls/certs/ca-bundle.crt  CApath: nonedebug(0): SSL connection using SSL_RSA_WITH_RC4_128_SHAdebug(0): Server certificate:debug(0): subject: CN=stream.twitter.com,OU=Twitter Security,O="Twitter, Inc.",L=San Francisco,ST=California,C=USdebug(0): start date: Oct 09 00:00:00 2013 GMTdebug(0): expire date: Dec 30 23:59:59 2016 GMTdebug(0): common name: stream.twitter.comdebug(0): issuer: CN=VeriSign Class 3 Secure Server CA - G3,OU=Terms of use at https://www.verisign.com/rpa (c)10,OU=VeriSign Trust Network,O="VeriSign, Inc.",C=USdebug(0): Server auth using Basic with user 'bubudee'debug(2): GET /1.1/statuses/sample.json HTTP/1.1Authorization: Basic YnVidWRlZTpkZWVidWJ1User-Agent: PycURL/7.29.0Host: stream.twitter.comAccept: */*debug(1): HTTP/1.1 401 Unauthorizeddebug(0): Authentication problem. Ignoring this.debug(1): WWW-Authenticate: Basic realm="Firehose"debug(1): Content-Type: text/htmldebug(1): Cache-Control: must-revalidate,no-cache,no-storedebug(1): Content-Length: 1243debug(1): Connection: closedebug(1): <html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/><title>Error 401 Unauthorized</title></head><body><h2>HTTP ERROR: 401</h2><p>Problem accessing '/1.1/statuses/sample.json'. Reason:<pre>    Unauthorized</pre></body></html>debug(0): Closing connection 0Who let the dogs out?:p^CGot ctrl+c, going down!


You can do this by catching the pycurl.error type. Ex:

try:    conn.perform()except pycurl.error, e:    errorCode, errorText = e.args    print 'We got an error. Code: %s, Text:%s'%(errorCode, errorText)