作者trenteric (專業社畜)
看板Python
標題[問題] import其他.py中的涵式請益
時間Tue Apr 19 22:56:19 2022
我會有a.py, b.py, c.py...等程式爬各網站
最後會全部import到x.py運行
我的chromedriver路徑是一串涵式
簡化後大概如下
---- a.py ----
def a_main():
driver = webdriver.Chrome(chromedriver())
driver.get('url')
---- x.py ----
from a.py import a_main
def chromedriver():
((函式內容 略))
return chromedriver_path
def x_main():
chromedriver()
a_main()
x_main
運行後結果
---name 'chromedriver' is not defined
不懂為何會報錯
我的x_main中已經先呼叫了chromedriver()
為何運行到a_main()時chromedriver又變成未定義了?
但如果把def chromedriver()放到a.py就不會報錯了
但這樣我就必須在abc...中都定義一次def chromedriver():
感覺有點冗
請問有辦法只在我的x.py中定義一次chromedriver()就好嗎?
-----
Sent from JPTT on my Google Pixel 6 Pro.
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 1.164.202.52 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Python/M.1650380186.A.E08.html
※ 編輯: trenteric (1.164.202.52 臺灣), 04/19/2022 23:00:13
推 ckbtlin318: 因為你一開始import a.py的時候 那個時候還沒有定義 04/19 23:01
→ ckbtlin318: chromedriver()這個function 試試看定義完後再import 04/19 23:03
→ trenteric: 照你的方式調整是ok的,但這樣等於我必須在abcd.py都定 04/19 23:08
→ trenteric: 義一次chromedriver,是否有辦法只定義一次就好? 可改變 04/19 23:08
→ trenteric: 架構或寫法 謝謝 04/19 23:08
→ papple23g: 把chromedriver()作為參數傳遞給a_main就可以了? 04/19 23:17
初學者不是很懂,該如何參數化?
推 lycantrope: 可以寫個driver.py from driver import chromedriver 04/19 23:50
推 germun: 再寫個e定義crhomedriver讓abcd去import e啊 04/20 00:13
此方法可行!! 樓上兩位大神請受小第一拜 m(_ _)m
這樣就不用在每個程式中重新定義chromedriver了
※ 編輯: trenteric (220.137.23.238 臺灣), 04/20/2022 00:22:48