[英]Python multiple functions with the same decorator execute in main
I created a decorator to walk through directories for several functions to do some file operations. 我创建了一个装饰器来遍历目录以执行一些函数来执行一些文件操作。 Every time when more than one functions with the decorator in the script, only the first one will execute.
每当脚本中的装饰器使用多个功能时,只会执行第一个装饰器。
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')
It seems like I've missed some important properties in Python? 似乎我错过了Python中的一些重要属性?
Your target_dir
defaults to .
您的
target_dir
默认为.
, the current working directory, if there's no command line argument given, and in your wrapper
function, the os.walk
function is always called with target_dir
, which, after the os.chdir
call, would refer to one of the subfolders of the first call to the decorated function, so os.walk
naturally would not be able to find any more subfolders under .
,即当前工作目录(如果未提供命令行参数),并且在
wrapper
函数中,始终使用target_dir
调用os.walk
函数,在os.chdir
调用之后,该os.chdir
将引用第一os.chdir
文件夹中的一个调用修饰后的函数,因此os.walk
自然无法在下找到更多子文件夹.
, which is already a subfolder. ,它已经是一个子文件夹。
You can fix this by getting the absolute path of target_dir
first: 您可以通过首先获取
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.