有基于project_item和分支的ssh命令正在运行。我不想在已经运行的project_item和分支组合上运行ssh命令,所以我尝试添加一个条件来检查project_item和分支组合是否已经解析,有关于如何添加它的想法吗?
for project_item in projects:
branch = manifest_data(project_item)
print "PROJECT_ITEM: " + project_item
print "BRANCH: " + branch
/*********condition to check if the project_item/branch combo is already parsed/***********
mft = manifest_table(project_item,branch)
if 'win32' in OS_Type and branch != 'PROJECT NOT ENBALED':
#print OS_Type
cmd = "\"\"%s\Git\\bin\sh.exe\" --login -c \"ssh -l user -p 29418 review-android.company.com gerrit query project:%s branch:%s --format=JSON status:open --commit-message --current-patch-set\"\" >> gerrit_output.txt" %(os.environ['ProgramFiles(x86)'], project_item,branch)
elif 'linux' in OS_Type:
#print OS_Type
cmd = "ssh -l user -p 29418 review-android.company.com gerrit query project:%s branch:%s --format=JSON status:open --commit-message --current-patch-set\"\" >> gerrit_output.txt" %(project_item,branch)发布于 2014-01-13 05:59:12
如果您只是想避免运行同一命令两次,您只需记住该命令,然后检查您是否已经运行了该命令:
# Create a set to remember your executed commands. Sets are better than
# lists here, since you will repeatedly check if an item exists.
# See: https://wiki.python.org/moin/TimeComplexity
executed_commands = set()
for project_item in projects:
# Your posted code...
identifier = hash((project_item, branch))
# check if command has already been executed
if identifier not in executed_commands:
executed_commands.add(identifier)
# Actually run cmd...发布于 2014-01-13 05:45:24
我不完全理解你的问题,但你似乎是在问如何检查一个函数是否已经被调用一次,以便只计算一次?
"memoize“模式很好地实现了这一点。一个版本的can be found here。
完整的代码如下所示:
import collections
import functools
class memoized(object):
'''Decorator. Caches a function's return value each time it is called.
If called later with the same arguments, the cached value is returned
(not reevaluated).
'''
def __init__(self, func):
self.func = func
self.cache = {}
def __call__(self, *args):
if not isinstance(args, collections.Hashable):
# uncacheable. a list, for instance.
# better to not cache than blow up.
return self.func(*args)
if args in self.cache:
return self.cache[args]
else:
value = self.func(*args)
self.cache[args] = value
return value
def __repr__(self):
'''Return the function's docstring.'''
return self.func.__doc__
def __get__(self, obj, objtype):
'''Support instance methods.'''
return functools.partial(self.__call__, obj)
@memoized
def fibonacci(n):
"Return the nth fibonacci number."
if n in (0, 1):
return n
return fibonacci(n-1) + fibonacci(n-2)
print fibonacci(12)它只是缓存函数的返回值。你可能需要一些更智能的缓存,然后你应该检查一个真正的缓存,当然,但看起来你只是在优化,所以这可能是一个开始。
Python中的缓存已经在这里讨论过了:Is there a Python caching library?
发布于 2014-01-13 05:59:14
为什么不简单地将已解析对象的散列存储在列表中?
parsed_list=[]
for project_item in projects:
branch = manifest_data(project_item)
item_hash = hash(branch+project_item)
print "PROJECT_ITEM: " + project_item
print "BRANCH: " + branch
if item_hash not in parsed_list:
parsed_list.append(item_hash)
# more codehttps://stackoverflow.com/questions/21080595
复制相似问题