运行 仅当使用 Python 给出标签或关键字时的方法

Run a method only if a tag or keyword is given using Python

我正在 Python 中编写 Selenium 测试并希望能够标记脚本的某些部分,以便在我从 cmd 行指定它时可以跳过这些部分。我希望的是这样的:

@run
def somemethod():
    print "this method should not run if the @run tag is False"

我想从那里做的事情是这样的:

python script_name.py @run=False

或者应该采用的任何格式。这应该会使其跳过该方法。

这显然可以用 if 语句来完成,如下所示:

if not run:
    somemethod()

或者把if语句放在方法里面。但是,我希望能够从命令行编写一个标记,而不是到处都有大量的 if 语句。是否存在这样的东西,或者它是否是我必须尝试创建的功能?

我在用什么:

Python 2.7.9
Selenium 2.44   
Windows 7 and Linux

您可以创建自定义装饰器并使用 argparse 模块检查是否存在命令行开关。像这样:

import argparse
from functools import wraps

parser = argparse.ArgumentParser()
parser.add_argument('-d', '--dont-run-test', dest='dont_run_test', action='store_true', default=False)
arguments = parser.parse_args()

def run(f):
    @wraps(f)
    def wrapper(*args, **kwargs):
        if not arguments.dont_run_test:
            return f(*args, **kwargs)
        else: # To demonstrate it works
            print 'Skipping test %s' % f.__name__
    return wrapper

@run
def my_test():
    print 'This should run only if the -d command line flag is not specified'

my_test()

示例输出:

>python2 annotate.py
This should run only if the -d command line flag is not specified

>python2 annotate.py -d
Skipping     test my_test