Python: передача переменной из 1-го сценария во 2-й сценарий и передача другой переменной из 2-го сценария в 1-й сценарий - PullRequest
0 голосов
/ 04 октября 2019

Это упрощенная версия скриптов. Я все еще работаю в процессе обучения, поэтому они очень грубые.

** movieInfo.py **

def castInfo():
    castMbrName = inputbox("Provide name")
    castPageURL = "https://www.cast_site.com/" + castMbrName
    # Most pages match this format. Some don't. For example: 
    #   "http://www.cast_site.com/" + castMbrFirstName + "-" + castMbrSecondName
    # or
    #   "http://www.cast_site.com/" + castMbrAliasName

    # To make sure I have the right page, I search for the cast member's name on it.
    sourceCastPage = requests.get(castPageURL, headers=hdr).text
    soupCastPage = BeautifulSoup(sourceCastPage, "lxml")
    try:
        castMbrNameOnPage = soupCastPage.find("div", attrs={"class":"xyz"}).text

        # If this succeeds, I use castPageURL in the rest of the script.
        cast_mbr_url = castPageURL
    except (AttributeError,TypeError):

        # If not, I want send castMbrName to castPageURL.py
        return castMbrName #<<see note below<<

        # Getting the value from castURL in castPageURL.url into movieInfo.py
        cast_mbr_url = checkCastNameURL()

castInfo()

# Do other things with cast_mbr_url
.
.
.

** castPageURL.py **

# This script will take the cast member's name, search the db and either add the name and url if not 
# found or return the url if found.

def checkCastNameURL():
    # This is a TinyDB setup containing the names and urls that don't match.
    db = TinyDB(castMbr_db.json)

    # I want to import the castMbrName variable from movieInfo.py into here.
    cast_name_req = castInfo()

    # When I manually provided the cast name, it worked. Now, I want to use castMbrName from movieInfo.py

    # Search the db for the cast member's name. If not found, get copy of correct url from site and add to db.
    if db.search(where("cast_name") == cast_name_req) == []:
    cast_name_url = simpledialog.askstring(
        title="",
        prompt="Paste cast member's url from site:",
        initialvalue="",
    ).strip()

    # Add name and url to db
    db.insert(
        {
            "cast_name": cast_name_req,
            "cast_url": cast_name_url,
        }
    )

    result = db.get(Query()["cast_name"] == castNameReq)
    castURL = result.get("cast_url")
    return castURL

Я хочу отправить переменную castMbrName из movieInfo.py в castPageURL.py и отправить castURL из castPageURL.py в movieInfo.py,Сценарии работают индивидуально, но я хочу включить castPageURL в movieInfo.

Моя проблема в том, что я не знаю, куда импортировать. Любое понимание будет приветствоваться.

Я пытался:

** movieInfo.py **

import castPageURL
From castPageURL import checkCastNameURL # with and without this

** castPageURL **

import movieInfo
from movieInfo import castInfo # with and without this as well

Я также пытался это:

** movieInfo.py **

import castPageURL
From castPageURL import checkCastNameURL # with and without this

** castPageURL **

from __main__ import *

Я даже пытался импортировать внутри функции вместо верхней частисценарий.

** movieInfo.py **

import castPageURL
From castPageURL import checkCastNameURL # with and without this

** castPageURL.py **

def checkCastNameURL():
    import movieInfo
    from movieInfo import castInfo # with and without this

Мне не удалось заставить оба сценария распознавать функции другого.

Кроме того, в части «кроме» «попробовать / исключить»блок, как только это будет сделано,

return castMbrName

как мне запустить это?

cast_mbr_url = checkCastNameURL()

Пожалуйста, дайте мне знать, если необходимы дальнейшие разъяснения.

1 Ответ

0 голосов
/ 04 октября 2019

Если вы собираетесь импортировать модуль, попробуйте удалить castInfo() из конца файла и заменить его на

if __name__ == "__main__":
   castInfo()

Это лучше, потому что это позволит вам запустить методmanulaly, вместо того, чтобы запускаться при импорте.

Также при импорте из синтаксиса используется from castPageURL import checkCastNameURL, а не From castPageURL import checkCastNameURL. Это простая ошибка, но постарайтесь запомнить, что python чувствителен к регистру.

С точки зрения того, где вы должны импортировать метод, вы должны сделать это в самом начале вашей программы.

Если вы хотите импортировать из вас, вам не нужно import castPageURL доfrom castPageURL import checkCastNameURL, но вам нужно сделать так, чтобы import castPageURL на самом деле import path\to\castPageURL.py

...