完全公开,我对编程完全陌生,所以我提前道歉。我正在开发这个 python 脚本,它将获取用户输入并在某些操作系统命令(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 语句,并且它工作正常......抱歉发了这么长的帖子,并提前致谢!
最佳答案
locals 指的是当前帧,其中没有定义ab
。它位于您的 globals()
内,
您可以这样访问它:
def pingz():
system('ping -c 5 %(ab)s' % globals())
关于python - python 脚本中的错误(对于编程来说非常陌生!),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37044092/