我有两个文件:
一个包含我所有的函数 funclib.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)
我还有另一个文件 scripts.py 将调用此函数。
import os
from selenium import webdriver
from selenium.webdriver.firefox.webdriver import WebDriver
from selenium.webdriver.common.action_chains import ActionChains
import time
import sys
sys.path.append('/Users/admin/Desktop/Suite/Global Scripts/')
from funcLib import *
deviceSelection();
def firsttri():
wd.find_element_by_name("Accept").click()
time.sleep(5)
wd.find_element_by_name("Sign In").click()
time.sleep(5)
wd.find_element_by_name("Need help?").click()
time.sleep(5)
wd.find_element_by_name("Close").click()
time.sleep(5)
firsttri();
当我执行 scripts.py 时,出现错误
wd.find_element_by_name("Accept").click()
NameError: global name 'wd' is not defined
不知道为什么。谁能帮帮我?
请您参考如下方法:
在这里,您对作用域在 Python 中的工作方式有点困惑。
当您调用 deviceSelection() 时,它不会在 scripts.py 文件中创建一个 wd global ,它在 funclib.py 文件中是全局的,这就是您不能调用它的原因。
有一些方法可以安排它以便全局使用,但它们很困惑,您不应该这样做。相反,您应该删除 global 的使用并返回 wd 对象。
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。
wd = deviceSelection()
一般来说,建议您使用 return 语句而不是 global 将变量从一个命名空间传递到另一个命名空间,因为它更清晰、更明确,并且可以避免混淆情况,例如这个。
