Skip to main content
 首页 » 编程设计

python之如何使python函数根据环境变量使用字典中的值

2024年09月07日9zhoujg

我正在使用 pytest 和 Appium 在 iOS 和 Android 设备上进行自动化测试。 请考虑以下事项:

some_locator:  
       { 
        'iOS': ('MobileBy.ACCESSIBILITY_ID', 'some_id'), 
        'Android': ('MobileBy.ID', 'another_id') 
        } 
 
def foo(): 
    bar = driver.find_element(some_locator) 
    return bar.text 

我想从命令行使用 'ios' 或 'android' 参数运行脚本,使函数 find_element 使用相应的元组值。 我也知道我可以这样做:

# conftest.py 
def pytest_addoption(parser): 
    parser.addoption("--platform", default="ios") 
 
@pytest.fixture 
def cmdopt(request): 
    return request.config.getoption("--platform") 
 
# some_file.py 
 
some_locator:  
       { 
        'iOS': ('MobileBy.ACCESSIBILITY_ID', 'some_id'), 
        'Android': ('MobileBy.ID', 'another_id') 
        } 
 
def foo(platform): 
    if platform == 'ios': 
        bar = find_element(*some_locator['ios']) 
    elif platform == 'android': 
        bar = find_element(*some_locator['android']) 
    return bar.text 

但坦率地说,我不喜欢那样,因为我必须在每个方法中添加这些 if block 。 有什么方便的方法吗?我的python不好,所以我想不出解决办法,请指教。

请您参考如下方法:

你不能直接使用platform变量来索引some_locator吗?即

def foo(platform): 
    return find_element(*some_locator[platform]).text 

实际上,some_locator 字典的作用与 if-elif 链相同。