首页 > 解决方案 > 缺少 1 个必需的位置参数?

问题描述

我不明白这段代码有什么问题?它一直给我一个错误。我不想创建一个类。它不断给我“主函数中缺少 1 个必需的位置参数‘选择’。有人有什么建议吗?脚本应该是一个菜单,所有功能都连接到主函数。我试着做 elif,希望它有所帮助。我可能需要使用“自我”

import socket
import uuid
import os
import re

HNAME=1
IP=2
MAC=3
ARP=4
ROUT=5
QUIT=6



def get_user_choice(choice):
    print("Network Toolkit Menu")
    print("_____________________________________")
    print("1. Display the Host Name")
    print("2. Display the IP Address")
    print("3. Display the MAC Address")
    print("4. Display the ARP Table")
    print("5. Display the Routing Table")
    print("6. Quit")
    print()
    
    choice = int(input("Enter your choice: "))
    print()
    return choice

def choicefun(choice):
   
    while choice > QUIT or choice < HNAME:
        
        choice = int(input("Please enter a valid number: "))
        print()
        
    return choice

def get_hostname(host):
    host=socket.gethostname()
    print("\n The host name is: ", host)
    #return host

def get_ipaddr(ipv4):
    ipv4=socket.gethostbyname()
    print("\n The IPv4 address of the system is: ", ipv4)
    #return ipv4

def get_mac(ele):
    print ("The MAC address is : ", end="") 
    print (':'.join(['{:02x}'.format((uuid.getnode() >> ele) & 0xff) 
    for ele in range(0,8*6,8)][::-1]))

def get_arp(line):
    print("ARP Table")
    with os.popen('arp -a') as f:
        data=f.read()
    for line in re.findall('([-.0-9]+)\s+([-0-9a-f]{17})\s+(\w+)',data):
        print(line)
    return line

def __pyroute2_get_host_by_ip(ip):
    print("Routing table\n: ")
    table=os.popen('route table')
    print(table)

def main(choice):
    counter=False
    while counter==False:
        get_user_choice()
        choicefun()
        if choice == 6:
            counter==True
        elif choice == 1:
            get_hostname()
        elif choice == 2:
            get_ipaddr()
        elif choice == 3:
           get_mac() 
        elif choice== 4:
            get_arp()
        elif choice == 5:
            __pyroute2_get_host_by_ip()

main()

标签: pythonself

解决方案


发生这种情况是因为您在main没有相应choice参数的情况下调用该函数:

def main(choice):
    ...
main()

您需要传递choice参数或从函数中删除choice参数。似乎choice主要由 定义get_user_choice(),在这种情况下,代码可以读取:

def main():
    counter=False
    while counter==False:
        choice = get_user_choice()
...

但是,该get_user_choice函数也有一个choice参数。由于此参数被覆盖,choice = int(input("Enter your choice: "))您可能希望将函数定义为:

def get_user_choice():
    ...

推荐阅读