Python cmd命令行工具类封装,加上中文注释,提供100个实例
- 打印当前目录下的所有文件和文件夹
Copy
import os
def listdir():
for item in os.listdir():
print(item)
- 创建一个文件夹
Copy
import os
def create_dir(dirname):
os.mkdir(dirname)
- 删除一个文件夹
Copy
import os
def delete_dir(dirname):
os.rmdir(dirname)
- 切换当前目录
Copy
import os
def change_dir(path):
os.chdir(path)
- 查看当前目录
Copy
import os
def current_dir():
print(os.getcwd())
- 重命名文件或文件夹
Copy
import os
def rename(src, dst):
os.rename(src, dst)
- 删除文件
Copy
import os
def delete_file(filename):
os.remove(filename)
- 复制文件
Copy
import shutil
def copy_file(src, dst):
shutil.copy(src, dst)
- 移动文件
Copy
扫描二维码关注公众号,回复:
14640959 查看本文章
![](/qrcode.jpg)
import shutil
def move_file(src, dst):
shutil.move(src, dst)
- 获取文件大小
Copy
import os
def get_file_size(filename):
size = os.path.getsize(filename)
print(size)
- 获取文件最后修改时间
Copy
import os
def get_file_mtime(filename):
mtime = os.path.getmtime(filename)
print(mtime)
- 获取文件权限
Copy
import os
def get_file_mode(filename):
mode = os.path.stat(filename).st_mode
print(oct(mode))
- 获取文件所有者
Copy
import os
def get_file_owner(filename):
owner = os.path.stat(filename).st_uid
print(owner)
- 获取文件所属组
Copy
import os
def get_file_group(filename):
group = os.path.stat(filename).st_gid
print(group)
- 判断文件是否存在
Copy
import os
def file_exists(filename):
exists = os.path.exists(filename)
print(exists)
- 判断文件是否为文件
Copy
import os
def is_file(filename):
isfile = os.path.isfile(filename)
print(isfile)
- 判断文件是否为目录
Copy
import os
def is_dir(dirname):
isdir = os.path.isdir(dirname)
print(isdir)
- 获取文件扩展名
Copy
import os
def get_file_extension(filename):
extension = os.path.splitext(filename)[1]
print(extension)
- 读取文件内容
Copy
def read_file(filename):
with open(filename, 'r') as f:
content = f.read()
print(content)
- 读取文件的前n行
Copy
def read_file_lines(filename, n):
with open(filename, 'r') as f:
for i in range(n):
line = f.readline()
print(line)
- 写入文件内容
Copy
def write_file(filename, content):
with open(filename, 'w') as f:
f.write(content)
- 追加文件内容
Copy
def append_file(filename, content):
with open(filename, 'a') as f:
f.write(content)
- 使用正则表达式搜索文件内容
Copy
import re
def search_file(filename, pattern):
with open(filename, 'r') as f:
content = f.read()
result = re.findall(pattern, content)
print(result)
- 替换文件内容
Copy
import re
def replace_file(filename, pattern, replacement):
with open(filename, 'r') as f:
content = f.read()
new_content = re.sub(pattern, replacement, content)
with open(filename, 'w') as f:
f.write(new_content)
- 检查文件是否为空
Copy
def is_file_empty(filename):
with open(filename, 'r') as f:
content = f.read()
if content:
print(False)
else:
print(True)
- 获取当前时间
Copy
import datetime
def get_current_time():
now = datetime.datetime.now()
print(now)
- 获取当前日期
Copy
import datetime
def get_current_date():
now = datetime.datetime.now()
print(now.date())
- 获取当前时间戳
Copy
import time
def get_current_timestamp():
timestamp = int(time.time())
print(timestamp)
- 计算时间差
Copy
import datetime
def time_diff(start, end):
diff = end - start
print(diff)
- 格式化时间
Copy
import datetime
def format_time(timestamp):
dt = datetime.datetime.fromtimestamp(timestamp)
formatted = dt.strftime('%Y-%m-%d %H:%M:%S')
print(formatted)
- 转换时间格式
Copy
import datetime
def convert_time_format(time_str, format1, format2):
dt = datetime.datetime.strptime(time_str, format1)
new_format = dt.strftime(format2)
print(new_format)
- 获取当前进程ID
Copy
import os
def get_pid():
pid = os.getpid()
print(pid)
- 获取当前用户名
Copy
import getpass
def get_username():
username = getpass.getuser()
print(username)
- 执行系统命令
Copy
import subprocess
def run_command(command):
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
output, error = process.communicate()
print(output.decode())
- 获取环境变量
Copy
import os
def get_env_var(varname):
value = os.environ.get(varname)
print(value)
- 设置环境变量
Copy
import os
def set_env_var(varname, value):
os.environ[varname] = value
- 删除环境变量
Copy
import os
def delete_env_var(varname):
del os.environ[varname]
- 获取系统信息
Copy
import platform
def get_system_info():
info = platform.uname()
print(info)
- 获取CPU信息
Copy
import psutil
def get_cpu_info():
cpu_count = psutil.cpu_count()
cpu_freq = psutil.cpu_freq()
cpu_percent = psutil.cpu_percent()
print(cpu_count, cpu_freq, cpu_percent)
- 获取内存信息
Copy
import psutil
def get_memory_info():
memory = psutil.virtual_memory()
print(memory)
- 获取磁盘信息
Copy
import psutil
def get_disk_info():
disk = psutil.disk_usage('/')
print(disk)
- 获取网络信息
Copy
import psutil
def get_network_info():
network = psutil.net_io_counters()
print(network)
- 获取进程信息
Copy
import psutil
def get_process_info(pid):
process = psutil.Process(pid)
name = process.name()
exe = process.exe()
cmdline = process.cmdline()
status = process.status()
memory_info = process.memory_info()
cpu_percent = process.cpu_percent()
print(name, exe, cmdline, status, memory_info, cpu_percent)
- 获取所有进程信息
Copy
import psutil
def get_all_processes():
processes = []
for process in psutil.process_iter():
processes.append(process.as_dict(attrs=['pid', 'name', 'username', 'cmdline', 'status']))
print(processes)
- 杀死进程
Copy
import psutil
def kill_process(pid):
process = psutil.Process(pid)
process.kill()
- 启动进程
Copy
import subprocess
def start_process(command):
process = subprocess.Popen(command, shell=True)
- 暂停进程
Copy
import psutil
def suspend_process(pid):
process = psutil.Process(pid)
process.suspend()
- 恢复进程
Copy
import psutil
def resume_process(pid):
process = psutil.Process(pid)
process.resume()
- 获取系统日志
Copy
import logging
def get_system_log():
logging.basicConfig(filename='system.log', level=logging.DEBUG)
with open('system.log', 'r') as f:
content = f.read()
print(content)
- 写系统日志
Copy
import logging
def write_system_log(message):
logging.basicConfig(filename='system.log', level=logging.DEBUG)
logging.debug(message)
- 获取随机数
Copy
import random
def get_random_number(start, end):
number = random.randint(start, end)
print(number)
- 获取随机字符串
Copy
import string
import random
def get_random_string(length):
letters = string.ascii_lowercase
result_str = ''.join(random.choice(letters) for i in range(length))
print(result_str)