python脚本出错(编程新手!)

2024-09-28 22:00:57 发布

您现在位置:Python中文网/ 问答频道 /正文

完全披露,我是完全新的编程,所以我提前道歉。我正在编写这个python脚本,它将获取用户输入并在某些OS命令(ping、traceroute、whois)中使用这些输入。虽然不完整,但脚本如下:

#!/usr/bin/python

from os import system

def pingz():

    system('ping -c 5 %(ab)s' % locals())

def trace_route():

    system('traceroute %(cd)s' % locals())

print("My Web Utility:")

print("____________________\n")

print(" 1)Ping a website/IP Address.\n")

print(" 2)Trace the route to a website/IP Address.\n")

print(" 3)Whois inforation.\n")

choice = raw_input("What would you like to do? \n")

if choice == '1':

    ab = raw_input("Please enter the Domain Name/IP Address:\n")

    pingz()

elif choice == '2':

    cd = raw_input("Please enter the Domain Name/IP Address:\n")

    trace_route() 

我在每个“选择”上都有两个错误。例如,如果我键入1,我会得到一个提示,要求输入域名/ip地址,当我输入时,得到的错误是:

Traceback (most recent call last):
File "./test2.py", line 19, in <module>
pingz()
File "./test2.py", line 6, in pingz
system('ping -c 5 %(ab)s' % locals())
KeyError: 'ab'

选择2也有类似的错误。我调用函数的方式有问题吗?有人能给我指一下正确的方向吗?我已经尝试过这个脚本的较小的实现(没有创建自己的函数)并且没有else/elif语句,它工作得很好。。。抱歉发了这么长的帖子,提前谢谢!你知道吗


Tags: theip脚本inputrawabaddress错误
2条回答

局部变量指的是当前帧,其中没有定义ab。它在你的globals()里面

您可以这样访问它:

def pingz():
    system('ping -c 5 %(ab)s' % globals())

函数中没有任何局部变量,因此locals()是一个空字典,因此它会引发KeyError。你知道吗

与其依赖于locals()(或globals())函数,您只需将变量传递给函数:

def pingz(host):
    system('ping -c 5 %s' % host)

.
.
.

ab = raw_input("Please enter the Domain Name/IP Address:\n")

pingz(ab)

与使用locals()globals()相比,该方法是优选的。 它更具可读性,更清晰,更不容易出错,特别是当您计划修改函数中的可变对象时。你知道吗

另外,由于globalslocals都是基本的字典,它们会强制您使用唯一的变量名,并且没有理由让2个函数的局部变量有唯一的名称(例如,ping和traceroute函数都应该有一个名为host的变量)。你知道吗

相关问题 更多 >