本文最后更新于283 天前,其中的信息可能已经过时,如有错误请发送邮件到270371528@qq.com
python内置函数总结
每次打比赛都在想有什么内置函数可以用,这次总结一下方便自己来找。
Python 的内置函数(Built-in Functions)
Python 内置函数是无需导入任何模块即可直接使用的函数,常见的有:
| 函数名 | 功能说明 | 示例 |
|---|---|---|
print() |
输出内容到控制台 | print("Hello") |
len() |
返回对象的长度 | len([1, 2, 3]) → 3 |
open() |
打开文件(高危函数) | open("file.txt").read() |
eval() |
执行字符串代码(高危) | eval("1+1") → 2 |
exec() |
执行动态代码块(高危) | exec("import os") |
input() |
接收用户输入 | name = input("Name?") |
range() |
生成整数序列 | range(5) → 0,1,2,3,4 |
type() |
返回对象类型 | type(123) → <int> |
__import__() |
动态导入模块(高危) | __import__("os") |
os 模块
os 是 Python 的 标准库模块,用于与操作系统交互,提供以下功能:
| 功能 | 示例代码 | 作用 |
|---|---|---|
| 打开文件 | os.popen('123.txt').read() |
打开文件并读取内容 |
| 执行系统命令 | os.system("ls") |
直接运行 Shell 命令 |
| 文件/目录操作 | os.listdir("/") |
列出目录内容 |
| 环境变量管理 | os.getenv("PATH") |
获取环境变量值 |
| 进程管理 | os.kill(pid, signal) |
结束指定进程 |
| 路径操作 | os.path.join("a", "b") |
安全拼接路径 |
subprocess模块
用途:更安全、更灵活地执行系统命令(替代 os.system、os.popen)。
示例:
import subprocess
# 执行命令并获取输出(推荐)
result = subprocess.run(["ls", "-l"], capture_output=True, text=True)
print(result.stdout)
# 替代 os.system
subprocess.call("echo Hello", shell=True)
# 替代 os.popen
output = subprocess.check_output("whoami", shell=True, text=True)
print(output)
优势:
- 避免
shell=True的安全风险(命令注入)。 - 支持更精细的控制(如超时、输入/输出重定向)。
__import__和import os的区别
1. 基本区别
| 特性 | import os |
__import__('os') |
|---|---|---|
| 类型 | 语句(不能用在表达式中) | 函数(可以用在任意表达式中) |
| 返回值 | 无(直接绑定到当前命名空间) | 返回模块对象 |
| 动态导入 | 不支持 | 支持 |
| 典型用途 | 常规代码中的模块导入 | 需要动态决定模块名的场景 |
2. 使用示例
(1) import os(静态导入)
import os
print(os.listdir('.')) # 直接使用
(2) __import__()(动态导入)
module_name = 'os' # 模块名可以是变量
os = __import__(module_name)
print(os.listdir('.'))
3. 关键差异点
-
动态性:
# 根据条件导入不同模块 lib = 'json' if condition else 'pickle' module = __import__(lib) -
字符串参数:
# 从字符串导入(常见于配置驱动的场景) __import__('os.path').join('a', 'b') -
嵌套导入:
# 导入子模块的正确方式 np = __import__('numpy.core.multiarray')
4. 安全注意事项
-
__import__()常被用于恶意代码:# 危险示例(不要在实际代码中使用!) __import__('os').system('rm -rf /') -
生产代码中应该:
- 优先使用
import语句 - 如果必须动态导入,要对模块名做严格校验
- 优先使用
5. 性能比较
import os稍快(编译器直接优化)__import__()有额外函数调用开销
6.题目用法
__import__()是动态字符串,用eval执行
import os是python语句,用exec执行
Q1: 如何列出所有内置函数?
print(dir(__builtins__)) # 查看所有内置函数
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BaseExceptionGroup', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EncodingWarning', 'EnvironmentError', 'Exception', 'ExceptionGroup', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'aiter', 'all', 'anext', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']

