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

仅当使用Python给出标记或关键字时才运行方法,python,annotations,Python,Annotations,我正在用Python编写Selenium测试,希望能够标记脚本的某些部分,以便在从cmd行指定时跳过这些部分。我希望是这样的: @run def somemethod(): print "this method should not run if the @run tag is False" import argparse from functools import wraps parser = argparse.ArgumentParser() parser.add_argumen

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

@run
def somemethod():
    print "this method should not run if the @run tag is False"
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()
我想从那里做的是:

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模块检查是否存在命令行开关。大概是这样的:

@run
def somemethod():
    print "this method should not run if the @run tag is False"
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

不要偷懒。您应该已经完成了if语句。当你得到一个答案的时候,有很多脚本,而且懒惰=丑陋。试图避免。。。