如何使python函数基于环境变量使用字典中的值?

如何使python函数基于环境变量使用字典中的值?,python,appium,pytest,python-appium,Python,Appium,Pytest,Python Appium,我正在使用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)

我正在使用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'
参数运行脚本,使函数
查找元素
使用相应的元组值。 我也知道我可以这样做:

# 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
块。
有什么方便的方法吗?我的python不好,因此我无法找到解决方案,请给出建议。

直接使用
平台
变量

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

您不能直接使用
平台
变量来索引
某些定位器
?i、 e

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

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

您可以这样编写代码,例如:def foo(平台):bar=find_元素(*some_locator[platform])返回bar.text。请确保您明智地处理KeyError异常。因此,obviuos!谢谢,我不知道为什么我没弄明白myself@NikBarch因为一旦你盯着自己的代码看了太久,明显的事情就会被忽略,这种情况一直发生在我身上。休息一下,回来,你会看到更多。非常感谢,乔!