如何在函数中使用局部变量,就像其他函数的全局变量变量一样



我写了一个简单的测试,它在某些网站上进行身份验证,解析HTML代码的某些部分,并将电子邮件发送到所需的邮箱。我想让一切都变得漂亮,我决定为这段代码定义函数。

我的代码:

from selenium.webdriver.support.ui import Select
from selenium.webdriver.chrome.options import Options
from selenium import webdriver
import smtplib
CHROME_PATH = '/usr/bin/google-chrome'
CHROMEDRIVER_PATH = '/usr/local/bin/chromedriver'
WINDOW_SIZE = "1024,768"
def pgi_auth(sitename, region_pgi, login_pgi, password_pgi):
    chrome_options = Options()
    chrome_options.add_argument("--headless")
    chrome_options.add_argument("--window-size=%s" % WINDOW_SIZE)
    chrome_options.binary_location = CHROME_PATH
    driver = webdriver.Chrome(executable_path=CHROMEDRIVER_PATH,chrome_options=chrome_options)
    driver.get(sitename)
    driver.find_element_by_id("LoginId").send_keys(login_pgi)
    driver.find_element_by_id("LoginPassword").send_keys(password_pgi)
    option = Select(
        driver.find_element_by_xpath("//select[@name='Region']")
    ).select_by_value(region_pgi)
    driver.find_element_by_id("submit").click()
    element = driver.find_element_by_id("TotalCurrentCharges-body").text
    current_charges = element.splitlines()[1]
    print(current_charges)
    driver.quit()
def send_email(host, port, from_addr, password, to_addr, subject, current_charges):
    BODY = "rn".join((
        "From: %s" % from_addr,
        "To: %s" % to_addr,
        "Subject: %s" % subject ,
        "",
        body_text
    ))
    server = smtplib.SMTP(host, port)
    server.starttls()
    server.login(from_addr, password)
    server.sendmail(from_addr, [to_addr], BODY)
    server.quit()
#for pgi_auth
sitename="https://invoiceaccess.pgiconnect.com"
login_pgi="my_secret_login"
password_pgi="my_secret_password"
region_pgi="us"
#for send_email
host = "mail.example.com"
port = "587"
from_addr = "test.mail@example.com"
password = "my_secret_password"
to_addr = "test.receive@example.com"
subject = "MY BALANCE:"
pgi_auth(sitename, region_pgi, login_pgi, password_pgi)
send_email(host, port, from_addr, password, to_addr, subject, current_charges)

在我的函数pgi_auth中,我接收变量current_charges我想在这个pgi_auth之外的这个变量用于函数send_email。当然,我可以在没有函数的情况下做到这一点,但我想尝试让一切都变得漂亮(也许我会使用 config),我怎样才能在函数之外获得这个变量?

你需要在方法中return关键字

def pgi_auth(sitename, region_pgi, login_pgi, password_pgi):
    .....
    .....
    return current_charges
....
....
subject = "MY BALANCE:"
current_charges = pgi_auth(sitename, region_pgi, login_pgi, password_pgi)
send_email(host, port, from_addr, password, to_addr, subject, current_charges)

相关内容

  • 没有找到相关文章

最新更新