简体   繁体   中英

TypeError when calling socket.connect(…)

I keep getting an error while running a relatively simple TCP client. The troublesome line is the call to socket.connect(..) which looks to through a TypeError. Any ideas why? I've put in hard coded values for now for host and port for now.

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/logging/__init__.py", line 846, in emit
    msg = self.format(record)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/logging/__init__.py", line 723, in format
    return fmt.format(record)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/logging/__init__.py", line 464, in format
    record.message = record.getMessage()
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/logging/__init__.py", line 328, in getMessage
    msg = msg % self.args
TypeError: not all arguments converted during string formatting
Logged from file run_42bets.py, line 70

# ------

#!/usr/bin/python

import importlib
import logging
import optparse
import os
import socket

SCRIPT_NAME = os.path.basename(__file__)
VERSION = SCRIPT_NAME + ' 1.0'

class TCPCommandSender:
    """Wrapper around TCP client for sending commands"""
    def __init__(self, host, port):
        """Setup connection to host:port"""
        logging.info("Connecting to server %s:%s", host, port)

        self.__host = host
        self.__port = port

        self.__socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.__socket.connect(("127.0.0.1", 2000))

    def __enter__(self):
        """Return TCPCommandSender instance"""
        return TCPCommandSender

    def __exit__(self, type, value, traceback):
        """Tear down connection if connected"""
        if self.__socket:
           logging.info("Disconnecting from server %s:%s", self.__host, self.__port)
           self.__socket.close()

    def send(self, cmd):
        """Send admin command to server and return received message"""
        try:
            self.__socket.sendall(cmd)
            return self.__socket.recv(1024)
        except socket.error, msg:
            logging.critical("Failed to send admin cmd; reason=%s", msg)
            return "ERROR"

def main():
    #customise logging
    logging.basicConfig(filename=SCRIPT_NAME + '.log', 
                        filemode='a',
                        format='%(asctime)s %(levelname)s %(message)s',
                        datefmt='%Y-%m-%d %H:%M:%S',
                        level=logging.INFO) 

    logging.info("Starting %s", SCRIPT_NAME)

    #define command line arguments
    parser = optparse.OptionParser("Usage: %prog [options]", version=VERSION)
    parser.add_option('--host', dest='host', help='Server to send commands to', type='string')
    parser.add_option('--port', dest='port', help='Server admin port to send commands to', type='int')
    parser.add_option('--config', dest='config', help='Python configuration module to configure algo', metavar='FILE')
    (options, args) = parser.parse_args()

    #check we have all required command line arguments
    if options.host and options.port and options.config:
        try:
            with TCPCommandSender(options.host, options.port) as cmd_sender:
                try:
                    logging.info("Running configuration module %s", options.config)
                    logging.info("Finished configuration module %s", options.config)
                except:
                    logging.critical("Error while running configuration module %s", options.config)
        except EnvironmentError, msg:
            logging.critical("Failed to connect to server %s:%s", options.host, options.port, msg)
    else:
        parser.error("Incorrect number/set of arguments provided, see --help")  

    logging.info("Ending %s", SCRIPT_NAME)

if __name__ == "__main__":
    main()

Your problem is this line:

logging.critical("Failed to connect to server %s:%s", options.host, options.port, msg)

Python is complaining that you gave it three things to put into the string ( options.host , options.port , and msg ), but you only gave it two places to put them (only two %s ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM