我正在处理我的第一个python脚本。我想在回调函数中使用变量:
def run(self, edit):
gitFolder = os.path.basename(gitRoot)
#Get branch
self.run_command(['git', 'rev-parse','--abbrev-ref','HEAD'], self.branchDone)
def branchDone(self, result):
build = "./Build-Release.ps1 " + gitFolder + " " + result +" -Deploy;"
print build
如何为方法branchDone提供gitFolder?
答案 0 :(得分:2)
只需从gitFolder
返回run
,然后在run
中致电branchcode
试试这个: -
def run(self, edit):
gitFolder = os.path.basename(gitRoot)
#Get branch
self.run_command(['git', 'rev-parse','--abbrev-ref','HEAD'], self.branchDone)
return gitFolder
def branchDone(self, result):
build = "./Build-Release.ps1 " + run() + " " + result +" -Deploy;" #run() returns gitfolders
print build
还有另一种方式
def run(self, edit):
self.gitFolder = os.path.basename(gitRoot)
#Get branch
self.run_command(['git', 'rev-parse','--abbrev-ref','HEAD'], self.branchDone)
def branchDone(self, result):
build = "./Build-Release.ps1 " + self.gitFolder + " " + result +" -Deploy;"
但它带来了一个问题,您需要在执行run
之前执行branchcode
函数,否则self.gitfolder
将被取消定义并引发Attribute error
。
答案 1 :(得分:1)
正如我所观察到的,这些是类方法,您可以定义一个类属性来跨它们共享gitFolder。
def run(self, edit):
self.gitFolder = os.path.basename(gitRoot)
#Get branch
self.run_command(['git', 'rev-parse','--abbrev-ref','HEAD'], self.branchDone)
def branchDone(self, result):
build = "./Build-Release.ps1 " + self.gitFolder + " " + result +" -Deploy;"
print build
答案 2 :(得分:1)
一种方法是使用functools.partial:
def run(self, edit):
gitFolder = os.path.basename(gitRoot)
#Get branch
callback = functools.partial(self.branchDone, gitFolder)
self.run_command(['git', 'rev-parse','--abbrev-ref','HEAD'], callback)
def branchDone(self, gitFolder, result):
build = "./Build-Release.ps1 " + gitFolder + " " + result +" -Deploy;"
print build
答案 3 :(得分:1)
如果您不需要branchDone
作为回调,请考虑将其定义为run
内的闭包:
from subprocess import check_output
def run_command(command, callback):
callback(check_output(command).strip())
class Foo(object):
def run(self, edit):
gitFolder = "some_magic"
def branch_done(result):
print "./Build-Release.ps1 " + gitFolder + " " + result + " -Deploy;"
run_command(['git', 'rev-parse','--abbrev-ref','HEAD'], branch_done)
Foo().run("edit")