我正在努力从命令行传递一些参数,到目前为止,代码看起来像这样:
class DeviceManager:
def __init__(self):
self.network_ip = self.__get_network_ip__()
self.devices = self.__get_devices__()
self.sort_by("id")
...other methods such as pick_by_rangeID(f,t)...
文件Tool.py:
import argparse
from Device_Manager import*
if __name__ == "__main__":
dm = DeviceManager()
parser = argparse.ArgumentParser()
parser.add_argument("method", help ="method to call")
parser.add_argument("-f", type = int, help ="from")
parser.add_argument("-t", type = int, help ="to")
args = parser.parse_args()
if args.method == "sbID":
dm.pick_by_range_ID(args.f,args.t)
我期望从命令行调用它为:python Tool.py sbID -f 5 -t 6
,这导致我的错误:TypeError: __init__() missing 1 required positional argument: 'message'
,据我所知,这发生在一个对象被初始化时,它的类缺少参数。令我惊讶的是,如果我像下面这样直接运行这个方法,异常不会发生。
dm = DeviceManager()
devs = dm.pick_by_range_ID(5,6)
我该如何解决这个问题?
编辑:添加pick_by_rangeID
方法:
def pick_by_range_ID(self,from_ID = 0, to_ID = 999999) -> list:
selected = []
for dev in self.devices:
id = dev.deviceID
if id >= from_ID and id <= to_ID:
selected.append(dev)
if len(selected) == 0:
raise ArgumentError("There are no IDs in that range.")
return selected
解决方案:问题在这一行:
raise ArgumentError("There are no IDs in that range.")
ArgumentError接受两个参数(class) ArgumentError(argument: Action | None, message: str)
我是这样解决的:
raise ArgumentError(None, "There are no IDs in that range.")