每个 Python 开发人员需要掌握的 5 个基本内置模块
wptr33 2025-01-31 15:39 21 浏览
# Import the sys module
import sys
# Get the Python version
python_version = sys.version
print("Python version:", python_version)
# Get the platform information
platform = sys.platform
print("Platform information:", platform)
# Get the Python path
python_path = sys.path
print("Python path:", python_path)
# Access command-line arguments
arguments = sys.argv
# Print the command-line arguments
print("Command-line arguments:", arguments)
# Get the first argument passed in
first_argument = sys.argv[1] if len(sys.argv) > 1 else None
print("First argument passed in:", first_argument)
# Terminate the program with a specific exit code
exit_code = 0 # Example exit code
sys.exit(exit_code) # Terminate the program with the specified exit code
- os模块: 使用os模块,我们可以执行与操作系统相关的各种操作。它就像一个方便的工具箱,用于管理文件、目录和检查它们是否存在。
# Import the os module
import os
# Get the current working directory
current_directory = os.getcwd()
# List files and directories in a directory
directory_path = "/path/to/directory"
directory_contents = os.listdir(directory_path)
# Check if a file or directory exists
path = "/path/to/file_or_directory"
exists = os.path.exists(path)
# Get information about a file
file_info = os.stat(path)
# Create a directory
os.mkdir("new_directory")
# Rename a file
os.rename("old_file.txt", "new_file.txt")
# Remove a file
os.remove("file_to_remove.txt")
# Change current working directory
os.chdir("/new/directory/path")
- math模块:将数学模块视为 Python 中值得信赖的计算器。它包含用于执行数学运算的函数,例如平方根、三角函数和四舍五入数。
# Import the math module
import math
# Perform basic mathematical operations
result_sqrt = math.sqrt(25) # Square root of 25
result_pow = math.pow(2, 3) # 2 raised to the power of 3
result_abs = math.abs(-5) # Absolute value of -5
# Calculate trigonometric functions
sine_value = math.sin(math.pi / 2) # Sine of π/2 (90 degrees)
cosine_value = math.cos(math.pi) # Cosine of π (180 degrees)
tangent_value = math.tan(math.pi/4) # Tangent of π/4 (45 degrees)
# Round numbers to the nearest integer
rounded_number_floor = math.floor(3.6) # Rounds down to 3
rounded_number_ceil = math.ceil(3.2) # Rounds up to 4
rounded_number_round = round(3.5) # Rounds to the nearest integer (4)
# Calculate logarithms
log_value = math.log(10, 2) # Logarithm of 10 to the base 2
# Calculate factorial
factorial_value = math.factorial(5) # Factorial of 5 (5!)
# Convert angles between degrees and radians
degrees_to_radians = math.radians(90) # Convert 90 degrees to radians
radians_to_degrees = math.degrees(math.pi / 2) # Convert π/2 radians to degrees
- random模块:它就像一顶魔术帽,可以拉出随机数或打乱列表,为我们的程序增添一点不可预测性。
# Import the random module
import random
# Generate random integers within a range
random_number = random.randint(1, 10) # Generates a random integer between 1 and 10
# Shuffle a list
my_list = [1, 2, 3, 4, 5]
random.shuffle(my_list) # Shuffles the list randomly
print("Shuffled List:", my_list)
# Generate a random float between 0 and 1
random_float = random.random() # Generates a random float between 0 and 1
print("Random Float:", random_float)
# Choose a random element from a sequence
my_sequence = ["apple", "banana", "orange", "grape"]
random_element = random.choice(my_sequence) # Chooses a random element from the sequence
print("Random Element:", random_element)
# Generate a random sample from a population
sample = random.sample(range(1, 101), 5) # Generate 5 unique random numbers from 1 to 100
print("Random Sample:", sample)
# Randomly select an element with replacement
random_element_with_replacement = random.choices(["A", "B", "C", "D"], k=3) # Select 3 elements with replacement
print("Random Element with Replacement:", random_element_with_replacement)
# Set the random seed for reproducibility
random.seed(1234) # Set the random seed to 1234
print(random.randint(1, 100)) # Output: 17
print(random.randint(1, 100)) # Output: 72
print(random.randint(1, 100)) # Output: 97
# Resetting the seed to the same value will produce the same sequence of random numbers
random.seed(1234)
print(random.randint(1, 100)) # Output: 17
print(random.randint(1, 100)) # Output: 72
print(random.randint(1, 100)) # Output: 97
- datatime模块: 是否需要在代码中使用日期和时间?这就是 datetime 模块派上用场的地方。它就像一个日历,可以帮助我们毫不费力地创建、格式化和操作日期和时间。
# Import the datetime module
import datetime
# Get the current date and time
current_datetime = datetime.datetime.now()
# Format a datetime object as a string
formatted_date = current_datetime.strftime("%Y-%m-%d %H:%M:%S") # Format as YYYY-MM-DD HH:MM:SS
print("Formatted Date:", formatted_date)
# Create a datetime object from a string
date_string = "2024-05-08"
converted_date = datetime.datetime.strptime(date_string, "%Y-%m-%d")
# Calculate the difference between two dates
date1 = datetime.datetime(2024, 5, 8)
date2 = datetime.datetime(2024, 5, 10)
date_difference = date2 - date1 # Difference between date2 and date1
print("Difference between two dates:", date_difference)
# Get the current date
current_date = datetime.date.today()
print(current_date.strftime("%Y-%m-%d")) # Print the current date in the format YYYY-MM-DD
# Calculate the difference between two datetime objects
timedelta = datetime.timedelta(days=7)
future_date = current_date + timedelta # Date 7 days from now
print("Future Date (7 days from now):", future_date)
# Get the day of the week
day_of_week = current_date.strftime("%A") # Full name of the day (e.g., Monday)
相关推荐
- Linux文件系统操作常用命令(linux文件内容操作命令)
-
在Linux系统中,有一些常用的文件系统操作命令,以下是这些命令的介绍和作用:#切换目录,其中./代表当前目录,../代表上一级目录cd#查看当前目录里的文件和文件夹ls#...
- 别小看tail 命令,它难倒了技术总监
-
我把自己以往的文章汇总成为了Github,欢迎各位大佬star...
- lnav:基于 Linux 的高级控制台日志文件查看器
-
lnav是一款开源的控制台日志文件查看器,专为Linux和Unix-like系统设计。它通过自动检测日志文件的格式,提取时间戳、日志级别等关键信息,并将多个日志文件的内容按时间顺序合并显示,...
- 声明式与命令式代码(声明模式和命令模式)
-
编程范式中的术语和差异信不信由你,你可能已经以开发人员的身份使用了多种编程范例。因为没有什么比用编程理论招待朋友更有趣的了,所以这篇文章可以帮助您认识代码中的流行范例。命令式编程命令式编程是我们从As...
- linux中的常用命令(linux常用命令和作用)
-
linux中的常用命令linux中的命令统称shell命令shell是一个命令行解释器,将用户命令解析为操作系统所能理解的指令,实现用户与操作系统的交互shell终端:我们平时输入命令,执行程序的那个...
- 提高工作效率的--Linux常用命令,能够决解95%以上的问题
-
点击上方关注,第一时间接受干货转发,点赞,收藏,不如一次关注评论区第一条注意查看回复:Linux命令获取linux常用命令大全pdf+Linux命令行大全pdf...
- 如何限制他人操作自己的电脑?(如何控制别人的电脑不让发现)
-
这段时间,小猪罗志祥正处于风口浪尖,具体是为啥?还不知道的小伙伴赶紧去补一下最近的娱乐圈八卦~简单来说,就是我们的小罗同事,以自己超强的体力,以及超强的时间管理能力,重新定义了「多人运动」的含义,重新...
- 最通俗易懂的命令模式讲解(命令模式百科)
-
我们先不讲什么是命令模式,先通过一个场景来引出命令模式,看看命令模式能解决什么样的问题。现在有一个渣男张三,他有还几个女朋友,你现在是不是还是单身狗,你就说你气不气?然后他需要每天分别叫几个女朋友起床...
- 互联网大厂后端必看!Spring Boot 中Runtime执行与停止命令?
-
你是否曾在使用SpringBoot开发项目时,遇到需要执行系统命令的场景?比如调用脚本进行文件处理,又或是启动外部程序?很多后端开发人员会使用Processexec=Runtime.get...
- Linux 常用命令(linux常用的20个命令面试)
-
日志排查类操作命令...
- Java字节码指令:if_icmpgt(0xA3)(java字节码使用的汇编语言)
-
if_icmpgt是Java字节码中的一条条件跳转指令,其全称是"IfIntegerCompareGreaterThan"。它用于比较两个整数值的大小。如果栈顶的第一个...
- 外贸干货|如何增加领英的曝光量和询盘
-
#跨境电商#...
- golang执行linux命令(golang调用shell脚本)
-
需求需要通过openssl生成rsa秘钥,然后保存该秘钥。代码实例packagemainimport("io/ioutil""bytes"&...
- LINUX磁盘挂载(linux磁盘挂载到windows)
-
1、使用root用户查看磁盘挂载情况:fdisk-l2、使用df查看当前磁盘挂载情况,根据和fdisk-l的结果进行对比,查看还有那些磁盘未使用3、挂载:mount磁盘挂载路径...
- Linux命令学习——nl命令(linux ln命令的使用)
-
nl命令主要功能为每一个文件添加行号,每一个输入的文件添加行号后发送到标准输出。当没有文件或文件为-时,读取标准输入...
- 一周热门
-
-
C# 13 和 .NET 9 全知道 :13 使用 ASP.NET Core 构建网站 (1)
-
因果推断Matching方式实现代码 因果推断模型
-
git pull命令使用实例 git pull--rebase
-
面试官:git pull是哪两个指令的组合?
-
git 执行pull错误如何撤销 git pull fail
-
git fetch 和git pull 的异同 git中fetch和pull的区别
-
git pull 和git fetch 命令分别有什么作用?二者有什么区别?
-
git pull 之后本地代码被覆盖 解决方案
-
还可以这样玩?Git基本原理及各种骚操作,涨知识了
-
git命令之pull git.pull
-
- 最近发表
- 标签列表
-
- git pull (33)
- git fetch (35)
- mysql insert (35)
- mysql distinct (37)
- concat_ws (36)
- java continue (36)
- jenkins官网 (37)
- mysql 子查询 (37)
- python元组 (33)
- mybatis 分页 (35)
- vba split (37)
- redis watch (34)
- python list sort (37)
- nvarchar2 (34)
- mysql not null (36)
- hmset (35)
- python telnet (35)
- python readlines() 方法 (36)
- munmap (35)
- docker network create (35)
- redis 集合 (37)
- python sftp (37)
- setpriority (34)
- c语言 switch (34)
- git commit (34)