关于getopt模块的报错解决

 在运行取代netcat的python程序时总是报这样的错误:

Traceback (most recent call last):
File "learnNetRep.py", line 147, in <module>
main()
File "learnNetRep.py", line 60, in main
client_sender(buffer)
File "learnNetRep.py", line 119, in client_sender
client_sock.connect((target, port))
File "/usr/lib/python2.7/socket.py", line 228, in meth
return getattr(self._sock,name)(*args)
TypeError: an integer is required

 之后经过仔细的查错分析,发现了代码中的一些问题(在getopt获取参数过程中):

port = a  # 这是错误的

  getopt函数示例:

options,args = getopt.getopt(sys.argv[1:],"hp:i:",["help","ip=","port="])

 这里返回的options是一个元组列表,即列表中每个元素都是元组,比如 [('-i','127.0.0.1'),('-p','80')],而socket.connect所需要的port要求是integer,所以需要进行转换。

port = int(a)  # 正确

 问题解决。

posted @ 2017-10-23 11:17  uaretheboss  阅读(696)  评论(0编辑  收藏  举报