Python 常用代码

遍历文件夹

import os

def main():
    g = os.walk(r"/Volumes/data/flutter_project/flupush/ast2vm/lib/declaration")
    for path, dir_list, file_list in g:
        for file_item in file_list:
            full_path = os.path.join(path, file_item)
            t = os.path.splitext(file_item)
            file_name = t[0]
            file_ext = t[1]
            

递归正则

递归正则需要待封装

def regular_format(result):
    result = result.replace('(', r'\(')
    result = result.replace(')', r'\)')
    result = result.replace('.', r'\.')
    result = result.replace('[', r'\[')
    result = result.replace(']', r'\]')
    result = result.replace('+', r'\+')
    result = result.replace('?', r'\?')
    result = result.replace('$', r'\$')
    return result

def recursive_regular(pattern, context):
    t = re.findall(pattern, context)
    result: str = t[0][0]
    count = result.count('{') - 1
    loop_count = 0
    while count > 0:
        result = regular_format(result)
        c = result + "([^}]+})"
        c = f"({c})"
        t = re.findall(c, context, flags=re.MULTILINE)
        # print(len(t))
        if len(t) == 0:
            x = 10
        while True:
            r = t[0]
            if isinstance(r, tuple):
                result = r[0]
            else:
                result = r
            break
        loop_count += 1
        d = result.count('{')
        count = d - 1 - loop_count
    return result
    
recursive_regular(r'(@override\s+bool operator ==([^}]+)})', context)

执行shell命令

ssh = subprocess.Popen(["/Volumes/data/flutter_sdk/bin/cache/dart-sdk/bin/dartfmt", write_path],
                       stdin=subprocess.PIPE,
                       stdout=subprocess.PIPE,
                       stderr=subprocess.PIPE,
                       universal_newlines=True,
                       bufsize=0)
                       
stdout_content = ssh.stdout.read()
stderr_content = ssh.stderr.read()
# ssh.stdin.write("输入参数!");
if stderr_content != '':
    # print(f"stderr: {stderr_content}")
    return False
else:
    with(open(write_path, mode='w')) as write_file:
        write_file.write(stdout_content)
ssh.stdin.close()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值