Python在main中执行具有相同decorator的多个函数

Python在main中执行具有相同decorator的多个函数,python,decorator,Python,Decorator,我创建了一个decorator来遍历多个函数的目录,以执行一些文件操作。每当脚本中有多个函数与decorator一起运行时,只有第一个函数会执行 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.

我创建了一个decorator来遍历多个函数的目录,以执行一些文件操作。每当脚本中有多个函数与decorator一起运行时,只有第一个函数会执行

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\u dir
默认为当前工作目录
,并且在您的
wrapper
函数中,
os.walk
函数总是使用
target\u dir
调用,这,调用
os.chdir
后,将引用第一次调用修饰函数的子文件夹之一,因此
os.walk
自然无法在
下找到更多的子文件夹,该子文件夹已经是子文件夹

您可以通过首先获取
target\u dir
的绝对路径来解决此问题:

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

如果没有给出命令行参数,您的
target\u dir
默认为当前工作目录
,并且在
wrapper
函数中,
os.walk
函数总是用
target\u dir
调用,在
os.chdir
调用之后,将引用第一次调用修饰函数的子文件夹之一,因此
os.walk
自然无法在已是子文件夹的
下找到更多子文件夹

您可以通过首先获取
target\u dir
的绝对路径来解决此问题:

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

对于subdirs中的dir:os.chdir(dir)
我觉得很可疑。如果您的初始当前工作目录是“C:\”,并且
subdirs
是[“foo”,“bar”],那么在第一次迭代中
chdir(dir)
将尝试导航到C:\foo。然后在第二次迭代中,
chdir(dir)
将尝试导航到C:\foo\bar而不是C:\bar。您需要在每次迭代结束时将chdir备份到原始的当前工作目录。。。。但是,除非您的程序因
FileNotFoundError
而崩溃,否则这可能不是问题的根本原因。只是需要注意一下。谢谢你指出错误!这就是这个问题的原因,与decorators无关。
对于subdirs中的dir:os.chdir(dir)
在我看来很可疑。如果您的初始当前工作目录是“C:\”,并且
subdirs
是[“foo”,“bar”],那么在第一次迭代中
chdir(dir)
将尝试导航到C:\foo。然后在第二次迭代中,
chdir(dir)
将尝试导航到C:\foo\bar而不是C:\bar。您需要在每次迭代结束时将chdir备份到原始的当前工作目录。。。。但是,除非您的程序因
FileNotFoundError
而崩溃,否则这可能不是问题的根本原因。只是需要注意一下。谢谢你指出错误!这是这个问题的原因,与装修工无关。