Reputation: 15006
I'm working on my first python script. I want to use a variable within a callback-function:
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
How do I make gitFolder available to the method branchDone?
Upvotes: 2
Views: 132
Reputation: 18567
If you don't need branchDone
except for as a callback, consider defining it as a closure inside 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")
Upvotes: 1
Reputation: 577
As I am observing, these are class methods, you can define a class attribute to share gitFolder across them.
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
Upvotes: 1
Reputation: 5061
simply return gitFolder
from run
and call run
in branchcode
Try this:-
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
There is another way
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;"
But it carries a problem that you need to execute the run
function before executing branchcode
, else self.gitfolder
will be undefined and raise Attribute error
.
Upvotes: 2
Reputation: 34272
One way would be using 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
Upvotes: 1