prachi prachi - 1 month ago 5
Python Question

No output is generated for main function in python TCP server

I wrote a program that would take command line arguments for the host name and port number. It works fine wen I remove the main function and as soon as I define a main function nothing is displayed.

import sys
import socket
from pip._vendor.distlib.compat import raw_input
import os
import threading

def Main(serverName,serverPort):
print('Initialising the socket')
serverName=sys.argv[1]
serverPort=int(sys.argv[2])
serverAddress=(serverName,serverPort)
#create the TCP/IP socket
clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientSocket.connect(serverAddress)
sentence = raw_input('enter string in lower case')
clientSocket.send(sentence)
modifiedSentence= clientSocket.recv(1024)
print ('from Server:'), modifiedSentence
clientSocket.close()

if __name__==main:
Main()

Answer

Your main does not run in this case. You need to adjust the if clause, further you need to grab the sys.argv and pass them to the Main() method since you wrote it to require the arguments as inputs.

if __name__ == '__main__':
    serverName=sys.argv[1]
    serverPort=int(sys.argv[2])
    Main(serverName,serverPort)
Comments