我得到了
NameError: global name 'git' is not defined
代表git.add(log_filename)
。我不明白为什么在repo = Repo(ABSOLUTE_PATH)
之前调用git = repo.git
和original_function = function(ABSOLUTE_PATH, GIT_WORKING_DIR, log_name, remove_logs)
。不应该git
对象可用于被调用的函数吗?
我想在这个实例中使用装饰器,因为单独的函数将使用类似的功能。如何让这个装饰工作?
def raw_git(function):
@wraps(function)
def wrapper(ABSOLUTE_PATH, GIT_WORKING_DIR,
log_name=None, remove_logs=None):
try:
repo = Repo(ABSOLUTE_PATH)
git = repo.git
except NoSuchPathError:
raise Exception("Error in finding local git path!")
original_function = function(ABSOLUTE_PATH, GIT_WORKING_DIR,
log_name, remove_logs)
return original_function
return wrapper
@raw_git
def git_add_log(ABSOLUTE_PATH, GIT_WORKING_DIR,
log_name=None, remove_logs=None):
log_name = GIT_WORKING_DIR + "/" + log_name
try:
git.add(log_filename)
git.commit(message="Removing oldest logs")
git.push()
except GitCommandError:
raise Exception("There was an error with git command "
"for removing oldest log(s)")
答案 0 :(得分:2)
git
是包装函数中的本地名称。它在该命名空间之外是不可见的,因此不在git_add_log
。
改为给该函数一个git
参数,并在调用包装函数时传入该对象:
def raw_git(function):
@wraps(function)
def wrapper(ABSOLUTE_PATH, GIT_WORKING_DIR,
log_name=None, remove_logs=None):
try:
repo = Repo(ABSOLUTE_PATH)
git = repo.git
except NoSuchPathError:
raise Exception("Error in finding local git path!")
original_function = function(git, ABSOLUTE_PATH, GIT_WORKING_DIR,
log_name, remove_logs)
return original_function
return wrapper
@raw_git
def git_add_log(git, ABSOLUTE_PATH, GIT_WORKING_DIR,
log_name=None, remove_logs=None):
log_name = GIT_WORKING_DIR + "/" + log_name
try:
git.add(log_filename)
git.commit(message="Removing oldest logs")
git.push()
except GitCommandError:
raise Exception("There was an error with git command "
"for removing oldest log(s)")