调用方法时出现名称错误

2024-04-20 14:00:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个文件:

一个包含我所有的功能函数库.py

import os 
from selenium import webdriver 
from selenium.webdriver.firefox.webdriver import WebDriver 
from selenium.webdriver.common.action_chains import ActionChains 
import time

        def deviceSelection():
            desired_caps = {}
            desired_caps['appium-version'] = '1.0'
            desired_caps['platformName'] = 'iOS'
            desired_caps['platformVersion'] = '8.2'
            desired_caps['deviceName'] = 'iPhone 6'
            desired_caps['app'] = os.path.abspath('/Users/admin/Library/Developer/Xcode/DerivedData/testapp-bfpdodvceugohuaaiiukkrcsrdqh/Build/Products/Debug-iphonesimulator/testapp.app')
            global wd
            wd = webdriver.Remote('http://0.0.0.0:4723/wd/hub', desired_caps)
            wd.implicitly_wait(60)

我还有另一个文件脚本.py将调用此函数。在

^{pr2}$

当我执行任务时脚本.py,我收到一个错误

^{3}$

不知道为什么。有人能帮我吗?在


Tags: 文件frompyimport功能脚本appos
1条回答
网友
1楼 · 发布于 2024-04-20 14:00:45

在这里,您对Python中的作用域如何工作有点困惑。在

当您调用deviceSelection()时,它并不是在scripts.py文件中创建wd,而是在funclib.py文件中是全局的,所以您不能调用它。在

有一些方法可以安排全局使用,但是它们很混乱,你不应该这样做。相反,你应该删除global和{}对象的使用。在

def deviceSelection():
    desired_caps = {}
    desired_caps['appium-version'] = '1.0'
    desired_caps['platformName'] = 'iOS'
    desired_caps['platformVersion'] = '8.2'
    desired_caps['deviceName'] = 'iPhone 6'
    desired_caps['app'] = os.path.abspath('/Users/admin/Library/Developer/Xcode/DerivedData/testapp-bfpdodvceugohuaaiiukkrcsrdqh/Build/Products/Debug-iphonesimulator/testapp.app')
    wd = webdriver.Remote('http://0.0.0.0:4723/wd/hub', desired_caps)
    wd.implicitly_wait(60)
    return wd

因为这样你就可以在scripts.py内设置wd。在

^{pr2}$

一般来说,建议您使用return语句而不是global将变量从一个命名空间传递到另一个命名空间,因为这样更清晰、更明确,并且避免了类似这样的混乱情况。在

相关问题 更多 >