Python Forum
command line input (arg parse) and data exchange
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
command line input (arg parse) and data exchange
#1
Hi guys hope you are all keeping cool.
i am having an issue with my python program that I was writing. I am trying to make small server & client program for high school students to motivate them to learn coding. but i am running into difficulties.
i was trying to get the user input from the command line (ubuntu to be precise) so like when a student enters the command to run the program with arguments (port number, buffer length & IP address) the program runs the client part of it. client then takes the length of buffer, takes the port number and ip from command line and assigns to the variables. it then generates a random number between 1 and 100 and sends to the port entered. Then when they enter the command to run the server side code with argument (port number only), the server listen to the port and receives the data and sends it back to the client.
the buffer length is to specify how much data the client will transmit to server.

the commands that student put are as follows.

./clientServer.py –t –p 5001 –l 1000 –ip 127.0.0.1
where -t to run the client part of code
-p to indicate port number
-l for buffer length
-IP for loop back address. (in real environment the same code will run on 2 different machines, one will run the client part of code and one will run the server part of code)

./clientServer.py –r –p 5001
where -r to run the server part of code
-p for the port number



but i am having issues in parsing data and running the file.

so if you guys can help me i would really appreciate that and will be really thankful to you guys.

here is the code

import socket
import time
import argparse
from random import randint


def main():


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

    #here is the argv parses 

    parser = argparse.ArgumentParser(description = 'sending data to server and back to client')
    parser.add_argument('-t', '--transmit', action='store_true', help='transmission')
    parser.add_argument('-r', '--receive', action='store_true', help='receiving')
    parser.add_argument('-ip', '--serveripAddr', default=('127.0.0.1'), required = True, help='this is ip address')
    parser.add_argument('-p', '--serverport', type=int, default=5001, required = True, help='this is port number')
    parser.add_argument('-l', '--bufferSize', type=int, default=8192, required  = True, help='this is buffer size')


    args = parser.parse_args()

    serverAddr = args.ip
    port = args.p 
    buffersize = args.l 


    if args.t:

	    clientSock.connect(port, serverAddr, buffersize)
	    number = randint(1,100)


	    dataOutStr= bin(number).replace("0b", "") # converts the numbers into binary before sending

	    dataOutBytes= dataOutStr.encode()
	    start = time.time()                       #start timer 
	    clientSock.sendall(dataOutBytes)           # sending data
	
        numBytes= len(dataOutBytes)
#=====================================================================================================
	    #loop until all data receivedd

	    dataInBytes= b''

	    while len(dataInBytes) < numBytes:
		    dataInBytes+= clientSock.recv(numBytes-len(dataInBytes))

		    if not dataInBytes:
	    	    	break

	        dataInStr= dataInBytes.decode()
	        remoteAddr= clientSock.getpeername()
	        print( "received", dataInStr, "back from server", remoteAddr)
	        print ("it took ", time.time()-start)

    	clientSock.close()


    elif args.r:

	    serverSock= socket.socket(socket.AF_INET,socket.SOCK_STREAM)
	    serverSock.bind(('', 5001))
	    serverSock.listen()

    	while True:

	    	connectSock, clientAddr= serverSock.accept()
		    print( "Connection from", clientAddr)
		    while True:   # keep receiving until client close
			    message = connectSock.recv()		
			
			    if not message:
				    break
			    
		    connectSock.sendall(message)

	    connectSock.close()

    else :
        print("something went wrong")


if __name__== '__main__':
       main()

The program is not Running and also not assigning the values to the variables.

can anyone help me please.
Reply
#2
check out: https://pymotw.com/3/argparse/
It's a very good tutorial for Argparse
Reply
#3
ok so,i have managed to sort out few things but the code is not functional. it is running, but its doing nothing.
seems like stuck in a non stop loop
can anyone help please....

import socket
import time
import argparse
from random import randint

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

#here is the argv pasrse 

parser = argparse.ArgumentParser(description = 'sending data to server and back to client')
parser.add_argument('-t', action='store_true', help='transmission')
parser.add_argument('-r', action='store_true', help='recieving')
parser.add_argument('-ip', default=('127.0.0.1'), help='this is ip address')
parser.add_argument('-p', type=int, default=5001, help='this is port number')
parser.add_argument('-l', type=int, default=8192, help='this is buffer size')


args = parser.parse_args()

hostAddr = args.ip
port = args.p 
bufferLenght = args.l 


if args.t:
        clientSock.connect((hostAddr, port))
        buffcounter = 0
        dataOutBytes = ''
        for x in range (bufferLenght):
                number = randint(1,9)
                dataOutStr= bin(number).replace("0b", "")
                dataOutBytes+= dataOutStr
                        
        dataOutBytes = dataOutStr.encode()       
        numBytes= len(dataOutBytes)
        start = time.time()
        clientSock.sendall(dataOutBytes)

#============================================================================
        #loop until all data recieved 
        dataInBytes= b''
        while len(dataInBytes) < numBytes:
                dataInBytes+= clientSock.recv(numBytes-len(dataInBytes))

                if not dataInBytes:
                        break

        dataInStr= dataInBytes.decode()
        remoteAddr= clientSock.getpeername()
        print( "received", dataInStr, "back from server", remoteAddr)
        print ("it took ", time.time()-start)

        clientSock.close()
      
elif args.r:

	serverSock= socket.socket(socket.AF_INET,socket.SOCK_STREAM)
	serverSock.bind(('', port))
	serverSock.listen()

	print ("The server is ready to receive!")


	while True:

		connectSock, clientAddr= serverSock.accept()
		print( "Connection from", clientAddr)

		while True:   # keep receiving until client close
			
			message = connectSock.recv(1024)		
			
			if not message:
				break
			    
		connectSock.sendall(message)

	connectSock.close()

if args.t:
        clientSock.connect((hostAddr, port))
        buffcounter = 0
        dataOutBytes = ''
        for x in range (bufferLenght):
                number = randint(1,9)
                dataOutStr= bin(number).replace("0b", "")
                dataOutBytes+= dataOutStr
                         
        dataOutBytes = dataOutStr.encode()       
        numBytes= len(dataOutBytes)
        start = time.time()
        clientSock.sendall(dataOutBytes)
 
#============================================================================
        #loop until all data recieved 
        dataInBytes= b''
        while len(dataInBytes) < numBytes:
                dataInBytes+= clientSock.recv(numBytes-len(dataInBytes))
 
                if not dataInBytes:
                        break
 
        dataInStr= dataInBytes.decode()
        remoteAddr= clientSock.getpeername()
        print( "received", dataInStr, "back from server", remoteAddr)
        print ("it took ", time.time()-start)
 
        clientSock.close()
its defiantly something in this part of the code..
Reply
#4
please do not send PM. Post here to share.
Reply
#5
Can anyone help please?
Reply
#6
Dos the network code work without argparse?
Simba Wrote:The program is not Running and also not assigning the values to the variables.
its defiantly something in this part of the code..
This is't helpful at all to understand the what's going on.
It's good idea to test the core stuff without any abstraction.
Keep it as simple as possible to start with,no argparse only the network code.
Then post that code with if getting errors(the whole Traceback message).
Reply
#7
it is working. and now even the argvparse is working but now the whole issue is that i am trying to run the randint() function to generate the same amount of data as buffer length specified by the user and then store it in the string before encoding and transmitting to the server.



hostAddr = args.ip
port = args.p 
bufferLenght = args.l 


if args.t:
        clientSock.connect((hostAddr, port))
        buffcounter = 0
        dataOutBytes = ''
        while bufferLenght >0:
                number = randint(1,9)
                dataOutStr= bin(number).replace("0b", "")
                dataOutBytes+= dataOutStr
                bufferLenght = bufferLenght - 1
                
        dataOutBytes = dataOutStr.encode()       
        numBytes= len(dataOutBytes)
        start = time.time()
        clientSock.sendall(dataOutBytes)
like literally this part is having issues.
Reply
#8
can anyone please help me?
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  input data validation plumberpy 2 278 Aug-11-2021, 12:04 PM
Last Post: plumberpy
  Presenting multiline data into single line aaronbuhu 1 237 Aug-05-2021, 10:57 AM
Last Post: jamesaarr
  Accessing varying command line arguements Rakshan 3 280 Jul-28-2021, 03:18 PM
Last Post: snippsat
  How to input & output parameters from command line argument shantanu97 1 682 Apr-13-2021, 02:12 PM
Last Post: Larz60+
  How to make input come after input if certain line inserted and if not runs OtherCode Adrian_L 6 930 Apr-04-2021, 06:10 PM
Last Post: Adrian_L
  Multi-line console input lizze 4 697 Dec-26-2020, 08:10 AM
Last Post: lizze
  Passing List of Objects in Command Line Python usman 7 1,103 Sep-27-2020, 03:45 PM
Last Post: ndc85430
  Using lambdas and map() to parse substrings in a single line Drone4four 5 1,218 Sep-20-2020, 10:38 AM
Last Post: snippsat
  bad input line 3 how t fix it youssef210 2 777 Aug-27-2020, 04:57 PM
Last Post: nilamo
  Parse BytesIO data GrahamL 2 719 Aug-19-2020, 05:09 PM
Last Post: bowlofred

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020