我一直想這個代碼,並從控制檯得到這個消息:Argparse錯誤試圖做簡單的UDP服務器客戶端
usage: Experimental.py [-h] [-p PORT] {client,server}
Experimental.py: error: the following arguments are required: role
我不能決定什麼是錯的,這是代碼:
import argparse, socket
from datetime import datetime
MAX_BYTES = 65535
def server(port):
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(('127.0.0.1', port))
print('Listening at {}'.format(sock.getsockname()))
while True:
data, address = sock.recvfrom(MAX_BYTES)
text = data.decode('ascii')
print('The client at {} says {!r}'.format(address, text))
text = 'Your data was {} bytes long'.format(len(data))
data = text.encode('ascii')
sock.sendto(data, address)
def client(port):
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
text = 'The time is {}'.format(datetime.now())
data = text.encode('ascii')
sock.sendto(data, ('127.0.0.1', port))
print('The OS assigned me the address{}'.format(sock.getsockname()))
data, address = sock.recvfrom(MAX_BYTES) # Danger!
text = data.decode('ascii')
print('The server {} replied {!r}'.format(address, text))
if __name__ == '__main__':
choices = {'client': client, 'server': server}
parser = argparse.ArgumentParser(description='Send and receive UDP locally')
parser.add_argument('role', choices=choices, help='which role to play')
parser.add_argument('-p', metavar='PORT', type=int, default=1060, help='UDP port (default 1060)')
args = parser.parse_args()
function = choices[args.role]
function(args.p)
這個網站是關於編程的問題,而不是關於如何運行別人寫的程序。 – user2357112
錯誤消息類告訴你什麼是錯誤的:一個叫做'role'的參數是必需的,但是當你從命令行運行程序時你沒有指定它。在這種情況下,您必須指定'client'或'server'。像'> python Experimental.py server'。 – jme