盒子
盒子
文章目录
  1. 前言
  2. Python 命令行传参
    1. 利用命令行参数列表获取参数
    2. 利用 argparse 模块获取参数
  3. 执行其他命令
  4. 文件扫描及读写
    1. 遍历目录
    2. 文件读写
    3. 正则表达式
  5. 异常捕获
  6. 面向对象
    1. 日志打印
  7. 模块化
    1. 包的概念
    2. 模块化命令传参

Python 实用语法总结

前言

本文是一篇根据日常开发整理的 Python 实用语法集合,简单记录并分享,方便自己回顾查阅。

Python 命令行传参

利用命令行参数列表获取参数

Python 可以通过 sys 模块获取命令行参数列表。

import sys

print(len(sys.argv))
print(sys.argv)

通过获取 argv 的参数列表,获取传参数组,然后根据入参顺序固定传参对应的操作,执行相关函数。当我们在 terminal 中输入 python test.py 时,就会输出命令行参数列表。

➜  PythonTest python test.py
1
['test.py']

从控制台输出可知, sys.argv 会将当前程序脚本名称也视为入参,而利用参数列表获取传参有两个弊端:参数传参表意不明,参数顺序不可改变。因此,接下来介绍另一种命令行参数获取方式。

利用 argparse 模块获取参数

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import sys
import argparse

global args

def read_args():
global args
parse = argparse.ArgumentParser()
parse.add_argument('-t', '--type', help='The Type of Process.', type=str, required=True)
args = parse.parse_args()

if __name__ == '__main__':
read_args()
type = args.type
print('Current Type ---> {}'.format(type))
print(len(sys.argv))
print(sys.argv)

与利用参数列表获取传参不同对于, argparse 模块需要创建参数解析实例,并且入参需要设置参数名称的简写、全写、类型,是否必须等属性。如果我们将入参设置为必须传参,那么当我们再次在 terminal 中输入 python test.py 时,就会报错,提示 argument -t/--type is required

➜  PythonTest python test.py
usage: test.py [-h] -t TYPE
test.py: error: argument -t/--type is required

当我们输入 python test.py -t aaa 命令时,就可以获得正确的输出结果。

执行其他命令

def run_command(cmd=''):
ret = os.system(cmd)
print("Execute Command: {}".format(cmd))
if ret != 0:
print("Error with Code: {}".format(ret))
sys.exit(-1)

文件扫描及读写

遍历目录

Python 用于扫描文件目录是很常见的应用场景,对于提高工作效率非常有助。比如,我们打印某个目录下的所有文件。

def traverse_dir(root='/'):
for parent, _, files in os.walk(root):
print('{} --->'.format(parent))
for _file in files:
print(_file)

除了文件遍历还可以进行文件读写

文件读写

def traverse_dir(root='/'):
for parent, _, files in os.walk(root):
print('{} --->'.format(parent))
for _file in files:
print(_file)
file_name, file_ext = os.path.splitext(_file)
file_path = os.path.join(parent, _file)
if file_ext == '.json':
with open(file_path, 'r') as json_file:
content = json_file.read()
print(content)
if file_ext == '.md':
with open(file_path, "w") as md_file:
md_file.write("# HelloWorld\n## My first doc\nHappy~~")

通过 with open(file_path, 'r') as 就可以对文件进行读写操作,使用了 with ... as 就不需要再对文件进行关闭,文件操作更加方便。

正则表达式

正则表达式用于字符串匹配,对于 Python 来说正则表达式常用的场景,查找匹配字符串,裁剪字符串等。

import re

def search_uuid(simulator_list=[]):
uuids = []
for item in simulator_list:
reg_result = re.search(r'\w{4,}-\w{4,}-\w{4,}-\w{4,}-\w{4,}', item)
if reg_result:
uuid = reg_result.group()
if uuid not in uuids:
uuids.append(uuid)
return uuids

def sub_number(origin_string='', replace_string=''):
content_line = re.sub(r'\d+', replace_string, origin_string)
return content_line

异常捕获

面向对象

日志打印

模块化

包的概念

模块化命令传参

支持一下
扫一扫,支持forsigner
  • 微信扫一扫
  • 支付宝扫一扫