如果用户不以命令行形式输入参数,有没有办法从自定义函数返回不同变量中的输入值?



我正在Kali Linux中制作一个基本的MAC转换器应用程序,该应用程序以以下形式进行参数:

python mac_changer.py -i <interface> -m <new MAC address>

在 PyCharm 中,我制作了以下函数来获取参数并返回它,我可以存储解析的返回值,但我也想允许程序询问用户接口和新的 MAC 地址,以防用户没有在命令中输入接口和 MAC。我可以以选项变量的形式返回解析的参数,我也可以返回输入的参数,但是有什么方法可以存储输入的参数吗?所有模块都已正确导入,以下代码是完整程序的一部分

def get_arguments():
parser = optparse.OptionParser()
parser.add_option("-i", "--interface", dest="interface", help="Interface to change its MAC address")
parser.add_option("-m", "--mac", dest="new_mac", help="New MAC address")
(options, arguments) = parser.parse_args()
if options.interface and options.new_mac:
if not options.interface:
#Code to handle error
parser.error(("[-] Please specify an interface, use --help for more info"))
elif not options.new_mac:
#Code to handle error
parser.error(("[-] Please specify a new MAC, use --help for more info"))
return options
else:
return input("Inteface> "),input("New MAC> ")
options = get_arguments()
printf(options.interface)
printf(options.new_mac)

这会从上面的命令行输出给定的参数,但我还想存储和使用代码使用输入函数和解析的参数从用户那里获得的参数。

您的代码基本上可以工作,但这有问题,因为您有两种不同的返回类型:

return options  # argparse.Namespace object
else:
return input("Inteface> "),input("New MAC> ")  # tuple of two strings
options = get_arguments()
printf(options.interface)
printf(options.new_mac)

如果在此代码上使用类型检查器并批注返回类型,则其中一行或另一行将引发错误。 如果您将options作为元组返回,并且调用方尝试访问options.interface,它将引发AttributeError,因为元组没有名为interface的字段。

最简单的解决方法是说该函数在任一情况下都返回interfacenew_mac为字符串元组:

from typing import Tuple
def get_arguments() -> Tuple[str, str]:
"""Returns interface, new_mac args, either from command line or user input"""
...

然后:

return options.interface, options.new_mac
else:
return input("Interface> "),input("New MAC> ")
interface, new_mac = get_arguments()
print(interface)
print(new_mac)

IMO 的一个稍微好一点的解决方案是使用NamedTuple,它基本上是一个元组,您可以为其命名,以及其各个字段的名称:

from typing import NamedTuple
class ChangerOptions(NamedTuple):
interface: str
new_mac: str
def get_arguments() -> ChangerOptions:
...
return ChangerOptions(options.interface, options.new_mac)
else:
return ChangerOptions(input("Interface> "),input("New MAC> "))
options = get_arguments()
print(options.interface)
print(options.new_mac)

如果你被迫在运行时调用一个没有类型注释和多个可能的返回类型的函数(即,你正在使用别人的代码,他们是一个可怕的人,希望你受苦(,可以在调用代码中通过执行以下操作来处理它:

return options  # argparse.Namespace object
else:
return input("Inteface> "),input("New MAC> ")  # tuple of two strings

options = get_arguments()
try:
# this will raise an AttributeError if no fields with these names
interface, new_mac = options.interface, options.new_mac
except AttributeError:
# whoops -- maybe it's a tuple?
# this will raise a TypeError if that wasn't right either...
interface, new_mac = options
print(interface)
print(new_mac)

最新更新