2015-11-09 74 views
1
import socket 
import re 
import sys 
import logging 
from __future__ import print_function 
def check_server(address, port): 
    #Create a TCP Socket 
    s = socket.socket() 
    print("Attempting to connect to %s on port %s" % (address, port)) 
    try:  
     s.connect((address, port) 
     print("Connected to %s on port %s" % (address, port)) 
     return True 
    except socket.error, e; 
     print("Connection to %s on port %s failed: %s" % (address, port, e)) 
     return False 

if __name__ == '__main__': 
    from optparse import OptionParser 
    parser = OptionParser() 

    parser.add_option("-a", "--address", dest="address", default='localhost', help="ADDRESS for server", metavar="ADDRESS") 
    parser.add_option("-p", "--port", dest="port", type="int", default=10001, help="PORT for server", metavar="PORT") 

    (options, arg) = parser.parse_args() 
    print 'options: %s, args: %s' % (options, args) 
    check = check_server(options.address, options.port) 
    print 'check_server returned %s' % check 

    sys.exit(not check) 
+0

的Python 3或2& –

+0

@AshwiniChaudhary因爲'從__future__進口print_function',我覺得OP是用Python 2 –

+1

@KevinGuan好吧好吧,'__future__'報表應在頂部放置的話,難怪我錯過了。 –

回答

1

將以下代碼

try:  
     s.connect((address, port) 
     print("Connected to %s on port %s" % (address, port)) 
     return True 
    except socket.error, e; 
     print("Connection to %s on port %s failed: %s" % (address, port, e)) 
     return False 

try:  
     s.connect((address, port)) 
     print("Connected to %s on port %s" % (address, port)) 
     return True 
    except socket.error, e; 
     print("Connection to %s on port %s failed: %s" % (address, port, e)) 
     return False 
+0

更多細節:OP忘記關閉一個'('這裏:'s.connect((地址,端口)'。 –

相關問題