在Python中,为什么要这个东东 __name__ == __main__

本文介绍了Python中main函数的特性,即直接执行脚本时main函数会被调用,而脚本被导入其他脚本时main函数会被忽略。还阐述了其用途,如文件可作为模块被其他程序调用,也能作为主程序运行,还可用于单元测试、提供API等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

One of those nice features of Python, that marks it as a language designed for developers (as opposed to one designed for tool vendors) is the ability to conditionally run some logic if you’re executing a script directly but ignore it if the script is being imported (“included”) by another script.

python 的main 方法是个很有意思的东东,如果你直接执行这个带有main的脚本,它会被调用。但是当这个脚本被import到其他的脚本的时候,main 会被忽略掉。惊奇不惊奇。

 

Why Does It Work This Way? 要这个东东干啥呢

You might naturally wonder why anybody would want this. Well, sometimes you want to write a .pyfile that can be both used by other programs and modules as a module and can be run as the main program. 

也许你会本能的猜测为什么会有人想要这个,有时候你写一个.py文件,它可以被其他程序和模块调用,有可以作为主程序运行。

  • Your module is a library, but you want to have a script mode where it runs some unit tests or a demo.

  • Your module is only used as a main program, but it has some unit tests, and the testing framework works by importing .py files like your script and running special test functions. You don't want it to try running the script just because it's importing the module.

  • Your module is mostly used as a main program, but it also provides a programmer-friendly API for advanced users.

创建一个 AI 防火墙是一个复杂的任务,通常涉及到网络监控、入侵检测系统(IDS)、威胁情报分析等多个方面,而且这超出了简单的 Python 脚本范围。然而,你可以用 Python 开发一个基本的规则检查防火墙模拟程序,它会检查特定的网络流量是否匹配预定义的安全策略。下面是一个简化的示例,展示了如何使用 Scapy 库来检测数据包并进行一些基本过滤: ```python from scapy.all import * # 定义安全规则 (这里仅作演示,实际应用需要更复杂) rules = { "allow": ["内部IP", "HTTPS"], "block": ["外部IP", "malicious_port"] } def is_packet_allowed(packet): src_ip = packet[IP].src dst_ip = packet[IP].dst sport = packet[TCP].sport if TCP in packet else None dport = packet[TCP].dport if TCP in packet else None for rule_type, patterns in rules.items(): if rule_type == "allow": if src_ip not in patterns or (sport and sport not in patterns) or (dport and dport not in patterns): return False elif rule_type == "block": if src_ip in patterns or (sport and sport in patterns) or (dport and dport in patterns): return False return True def firewall_sniffer(filter_string=""): packets = sniff(iface="eth0", prn=lambda x: print("Packet:", x.summary()) if is_packet_allowed(x) else None, filter=filter_string) if __name__ == "__main__": firewall_sniffer() ``` 这个脚本只是一个基础的网络嗅探器,它会捕获网络包,并根据定义的规则来判断是否允许。要构建真正的 AI 防火墙,你需要集成机器学习模型(如异常检测或基于深度学习的行为分析),并且实时更新模型来应对新的威胁。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值