Skip to main content
 首页 » 编程设计

python之Twisted ExtendSelected Reactor 错误

2025年04月02日14mengfanrong

我从 git hub 上的 txtnettools 包中提取了以下代码代码大部分是不完整的所以我试图弄清楚如何实际使代码发送我需要调用的数据包我认为 sendEcho() 方法作为 react 器所以我添加了适当的行。

from random import randint 
import socket 
import struct 
 
from twisted.internet.protocol import DatagramProtocol 
 
# needs to be run with sudo, so let's add the dev path 
import sys 
sys.path.insert(0, ".") 
 
from txnet.icmp import * 
from txnet.reactor import reactor 
 
 
UDP_PORT_MIN = 33434 
UDP_PORT_MAX = 33534 
 
 
def get_remote_port(): 
    return randint(UDP_PORT_MIN, UDP_PORT_MAX) 
 
 
class Pinger(ICMP): 
 
      def sendEcho(self): 
          print "Sending echo ..." 
          src = "192.168.1.1" 
          print src 
          #dst = "127.0.0.1" 
          #dst = "192.168.1.1" 
          #dst = "192.168.100.1" 
          dst = "74.125.45.100" 
          self.transport.connect(dst, get_remote_port()) 
          # Construct a ping packet (with useless payload data). 
          packet = Packet(src=src, dst=dst, type=ECHO_REQUEST, payload="txNetTools ping") 
          raw = packet.getDatagram() 
          self.transport.write(packet.getDatagram()) 
 
     def startProtocol(self): 
         print "Transport is:", self.transport 
         print "Transport class is:", self.transport.__class__ 
         print "self is:", self 
         self.sendEcho() 
 
     def connectionRefused(self): 
         print "Connection refused ..." 
         print "Host:", self.transport.getHost() 
         print "Remote host:", self.transport._connectedAddr 
         print "Connected:", self.transport.connected 
         print "Disconnected:", self.transport.disconnected 
         print "Data buffer:", self.transport.dataBuffer 
 
 reactor.Pinger.sendEcho() #Throwing error  
 reactor.listenICMP(0, Pinger()) 
 reactor.run() 

Rector.pinger.sendEcho() 但是,当我运行此脚本时,出现以下错误。

 Traceback (most recent call last): 
   File "ping.py", line 54, in <module> 
   reactor.Pinger.sendEcho() 
 AttributeError: 'ExtendedSelectReactor' object has no attribute 'Pinger' 

谷歌搜索“ExtendedSelectRector error”或任何接近的结果实际上没有解决方案或喋喋不休。谢谢

编辑:这里是源项目github https://github.com/oberstet/txnettools

请您参考如下方法:

答案完全取决于我如何访问 Pinger 类。更正后的代码行是

 reactor.callWhenRunning(Pinger().sendEcho) 

代替:

 reactor.Pinger.sendEcho() 

您需要向 react 器指定在您创建新 react 器时如何以及如何延迟自身。