tags:

views:

131

answers:

4

Hi

I have a simple question about Python:

I have another Python script listening on a port on a Linux machine. I have made it so I can send a request to it, and it will inform another system that it is alive and listening.

My problem is that I don't know how to send this request from another python script running on the same machine (blush)

I have a script running every minute, and I would like to expand it to also send this request. I dont expect to get a response back, my listening-script postes to a database.

In Internet Explorer, I write like this: http://192.168.1.46:8193/?Ping I would like to know how to do this from Python, and preferably just send and not hang if the other script is not running.

thanks Michael

A: 

This is a bit outside my knowledge, but maybe this question might help?

Ping a site in Python?

Paul D. Waite
A: 

Considered Twisted? What you're trying to achieve could be taken straight out of their examples. It might be overkill, but if you'll eventually want to start adding authentication, authorization, SSL, etc. you might as well start in that direction.

Alex Brasetvik
+3  A: 

It looks like you are doing an HTTP request, rather than an ICMP ping.

urllib2, built-in to Python, can help you do that.

You'll need to override the timeout so you aren't hanging too long. Straight from that article, above, here is some example code for you to tweak with your desired time-out and URL.

import socket
import urllib2

# timeout in seconds
timeout = 10
socket.setdefaulttimeout(timeout)

# this call to urllib2.urlopen now uses the default timeout
# we have set in the socket module
req = urllib2.Request('http://www.voidspace.org.uk')
response = urllib2.urlopen(req)
Oddthinking
There is no need to use `socket`; `urllib2.urlopen()` has `timeout` keyword argument. See my answer: http://stackoverflow.com/questions/1935939/python-send-cmd-on-socket/1936923#1936923
J.F. Sebastian
Yes, J.F. Sebastian is right. A timeout has been added in Python 2.6, so if you are using that, you can avoid affecting all the sockets.
Oddthinking
+1  A: 
import urllib2

try:
    response = urllib2.urlopen('http://192.168.1.46:8193/?Ping', timeout=2) 
    print 'response headers: "%s"' % response.info()
except IOError, e:
    if hasattr(e, 'code'): # HTTPError
        print 'http error code: ', e.code
    elif hasattr(e, 'reason'): # URLError
        print "can't connect, reason: ", e.reason
    else:
        raise # don't know what it is
J.F. Sebastian
Note: Requires Python 2.6.
Oddthinking