簡體   English   中英

具有相同裝飾器的Python多個函數在main中執行

[英]Python multiple functions with the same decorator execute in main

我創建了一個裝飾器來遍歷目錄以執行一些函數來執行一些文件操作。 每當腳本中的裝飾器使用多個功能時,只會執行第一個裝飾器。

import os
import re
import sys


def oswalk_deco(func):
    def wrapper(filename, *args):
        subdirs = [os.path.abspath(x[0]) for x in os.walk(target_dir)]
        subdirs.remove(os.path.abspath(target_dir))
        for dir in subdirs:
            os.chdir(dir)
            for item in os.listdir('.'):
                p = re.match(filename, item)
                if isinstance(p, re.Match):
                    match = p.group()
                    func(match, *args)
    return wrapper


def str2uni(string):
    if isinstance(string, str):
        return string.encode('utf8').decode('unicode_escape')
    else:
        print('Function "str2uni(string)" only accept strings.')
        exit()


@oswalk_deco
def sub_string(filename, regex, substr):
    with open(filename, 'r') as file:
        content = file.read()
    with open(filename, 'w') as file:
        content = re.sub(regex, substr, content)
        file.write(content)


@oswalk_deco
def regex_print(filename, string):
    with open(filename, 'r') as file:
        content = file.read()
        relist = re.findall(string, content)

    if filename[0] == 'u':
        print({str2uni(f'\\u{filename[1:-4]}'): relist})
    elif isinstance(re.match(r'code\d{2}-u.+', filename), re.Match):
        print({str2uni(f'\\{re.search("u[0-9a-z]{4,5}", filename).group()}'): relist})


@oswalk_deco
def docname_format(filename):
    with open(filename, 'r') as file:
        content = file.read()
    with open(filename, 'w') as file:
        content = re.sub(r'docname=".*"', f'docname="{filename}"', content)
        file.write(content)


if __name__ == '__main__':
    if len(sys.argv) == 1:
        target_dir = '.'
    else:
        target_dir = sys.argv[1]

    regex_print('.*\.svg', 'docname=".*"')
    regex_print('.*\.svg', 'stroke:none')
    sub_string('.*\.svg', 'docname=".*"', 'docname="stackoverflow.svg')

似乎我錯過了Python中的一些重要屬性?

您的target_dir默認為. ,即當前工作目錄(如果未提供命令行參數),並且在wrapper函數中,始終使用target_dir調用os.walk函數,在os.chdir調用之后,該os.chdir將引用第一os.chdir文件夾中的一個調用修飾后的函數,因此os.walk自然無法在下找到更多子文件夾. ,它已經是一個子文件夾。

您可以通過首先獲取target_dir的絕對路徑來解決此問題:

if len(sys.argv) == 1:
    target_dir = '.'
else:
    target_dir = sys.argv[1]
target_dir = os.path.abspath(target_dir)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM