0

运行相对简单的 TCP 客户端时,我不断收到错误消息。麻烦的线是对 socket.connect(..) 的调用,它通过 TypeError 查找。任何想法为什么?我现在已经为主机和端口输入了硬编码值。

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()
4

1 回答 1

2

你的问题是这一行:

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

Python 抱怨你给了它三个东西放在字符串中(options.host,options.portmsg),但是你只给了它两个地方来放它们(只有两个%s)。

于 2012-09-01T21:47:35.593 回答