gpt4 book ai didi

python - 如何替换python3中的has_key?

转载 作者:行者123 更新时间:2023-12-01 01:16:06 25 4
gpt4 key购买 nike

我尝试安装Auto-SelfControl执行此命令时卡住了:

sudo /usr/bin/python auto-selfcontrol.py

它显示错误:

AttributeError: 'dict' object has no attribute 'has_key'

我正在寻找解决方案,最终将 has_key 替换为 in 运算符,但由于我只了解 python 的基础知识,因此代码对我来说相当复杂。

有 3 个地方使用了 has_key,你能帮我更改它以便我可以使用 python3 运行吗?

1.

def check_if_running(username):
""" checks if self-control is already running. """
defaults = get_selfcontrol_settings(username)
return defaults.has_key("BlockStartedDate") and not NSDate.distantFuture().isEqualToDate_(defaults["BlockStartedDate"])

2-4。

def check_config(config):
""" checks whether the config file is correct """
if not config.has_key("username"):
exit_with_error("No username specified in config.")
if config["username"] not in get_osx_usernames():
exit_with_error(
"Username '{username}' unknown.\nPlease use your OSX username instead.\n" \
"If you have trouble finding it, just enter the command 'whoami'\n" \
"in your terminal.".format(
username=config["username"]))
if not config.has_key("selfcontrol-path"):
exit_with_error("The setting 'selfcontrol-path' is required and must point to the location of SelfControl.")
if not os.path.exists(config["selfcontrol-path"]):
exit_with_error(
"The setting 'selfcontrol-path' does not point to the correct location of SelfControl. " \
"Please make sure to use an absolute path and include the '.app' extension, " \
"e.g. /Applications/SelfControl.app")
if not config.has_key("block-schedules"):
exit_with_error("The setting 'block-schedules' is required.")
if len(config["block-schedules"]) == 0:
exit_with_error("You need at least one schedule in 'block-schedules'.")
if config.get("host-blacklist", None) is None:
print("WARNING:")
msg = "It is not recommended to directly use SelfControl's blacklist. Please use the 'host-blacklist' " \
"setting instead."
print(msg)
syslog.syslog(syslog.LOG_WARNING, msg)

最佳答案

解决方案的正式来源在这里:https://portingguide.readthedocs.io/en/latest/dicts.html

TL;DR 是这样的:

some_dict.has_key('some key')

现在是:

'some key' in some_dict

所以,在你的代码中:

return defaults.has_key("BlockStartedDate") and not NSDate.distantFuture().isEqualToDate_(defaults["BlockStartedDate"])

变成:

return "BlockStartedDate" in defaults and not NSDate.distantFuture().isEqualToDate_(defaults["BlockStartedDate"])

类似地,类似这样的行:

if not config.has_key("selfcontrol-path"):
# do something

变得像:

if "selfcontrol-path" not in config:
# do something

请注意,您也可以在配置中编写if not "selfcontrol-path":,但上面给出的示例被认为更Pythonic,应该是首选。

关于python - 如何替换python3中的has_key?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54337239/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com