python - reading port number as an argument and do stuff -


i wrote following script in python:

#!/usr/bin/python  import socket import sys import os  host=sys.argv[1] port=sys.argv[2]   if len(sys.argv) != 3:     print 'usage: python %s <hostname> <portnumber>' % (sys.argv[0])     sys.exit();  try:         s=socket.socket(socket.af_inet, socket.sock_stream) except socket.error, msg:         print 'failed creat socket. error code: ' + str(msg[0]) + ' error message: ' + msg[1]         sys.exit();  try:         host_ip=socket.gethostbyname(host)  except socket.gaierror:         print 'host name not resolved. exiting...'         sys.exit();  print 'ip address of ' + host + ' ' + host_ip + ' .'  try:     s.connect((host_ip, port)) #or s.connect((host_ip, sys.argv[2])) except socket.error, (value,message):     if s:         s.close();     print 'socket connection not established!\t' + message     sys.exit(1);  print 'socket connected ' + host + 'on ip ' + host_ip + 'on port number ' + port + '.' 

but when run error occures:

s.connect((host_ip, port)) return getattr(self._sock,name)(*args) typeerror: integer required 

what wrong here?

thanks

you should use argparse process arguments. provides many useful features in addition making easy fix immediate problem (not making port number integer). replace

host=sys.argv[1] port=sys.argv[2]   if len(sys.argv) != 3:     print 'usage: python %s <hostname> <portnumber>' % (sys.argv[0])     sys.exit(); 

with

import argparse p = argparse.argumentparser() p.add_argument("host") p.add_argument("port", type=int) args = p.parse_args() # , optionally host = args.host port = args.port 

Comments

Popular posts from this blog

how to proxy from https to http with lighttpd -

android - Automated my builds -

python - Flask migration error -