如何使用if __name__ ==' __ -main __”:構(gòu)造腳本執(zhí)行?
Jun 22, 2025 am 12:48 AM當(dāng)Python腳本中的__name__ == "__main__"條件成立時,表示該文件被直接運(yùn)行而非被導(dǎo)入。 1. __name__是Python的內(nèi)置變量,直接運(yùn)行腳本時其值為"__main__",被導(dǎo)入時則為模塊名;2. 使用此結(jié)構(gòu)可控制僅在直接運(yùn)行時執(zhí)行特定代碼,如測試或演示邏輯;3. 結(jié)構(gòu)上應(yīng)先定義函數(shù),再將需單獨運(yùn)行的代碼置於該條件塊內(nèi);4. 優(yōu)點包括避免導(dǎo)入時副作用、增強(qiáng)模塊復(fù)用性、便於添加測試代碼;5. 注意縮進(jìn)正確、避免相對導(dǎo)入問題、保持主塊簡潔。此機(jī)制有助於編寫靈活且乾淨(jìng)的代碼。
You'll often see the if __name__ == "__main__":
line in Python scripts, and it's super useful for controlling whether code runs when the file is executed directly or just imported. It basically checks if the script is being run as the main program rather than being imported into another script.
Here's how to use this pattern effectively:
What does __name__
mean?
In Python, every module has a built-in variable called __name__
. When you run a script directly (like typing python script.py
), Python sets __name__
to "__main__"
. But if that same script is imported into another script ( import script
), then __name__
gets set to the name of the file instead — like "script"
.
So this line:
if __name__ == "__main__":
…is checking whether the current file is being run directly. If yes, it executes whatever's indented under that condition.
This is really handy when you want to write reusable modules that can also behave like standalone programs.
How to structure your script with it
A common way to use this is by defining functions first, maybe even ones that could be reused elsewhere, and putting the part that should only run when the file is executed directly inside the if __name__ == "__main__":
block.
Here's a simple example:
def greet(name): print(f"Hello, {name}!") if __name__ == "__main__": greet("Alice")
- If you run this directly:
python script.py
, it will printHello, Alice!
. - If you import it from somewhere else:
import script
, nothing will happen automatically — which is good, because maybe you just wanted access to thegreet()
function.
This keeps things clean and avoids unwanted behavior when importing.
Why you'd want to use it
There are a few practical reasons people use this construct:
- Avoid side effects on import : You don't want code to run just because it was imported.
- Make reusable modules : You can share functions without running extra code unless needed.
- Add test/demo blocks : Sometimes you'll include a demo section or unit tests inside the
__main__
block so you can test functionality quickly.
For instance, imagine writing a math utility file. You define a bunch of functions, but you also want a quick way to test them out. Just put a little test section inside the __main__
block. That way, anyone who imports your file doesn't get all the test output unless they specifically want it.
A few gotchas and tips
- The code under
if __name__ == "__main__":
must be indented properly — otherwise, it won't run when expected. - You can have multiple lines inside that block — even call other functions or read input.
- Be careful about relative imports if you're working in packages — sometimes the behavior can surprise you.
- Don't overdo it — keep the
__main__
block short and focused. It's not meant for large logic sections.
One thing that trips people up is thinking that anything after that block will always run, no matter what. But actually, everything outside that conditional will run whether the file is imported or executed directly.
So if you have:
print("Top of the file") if __name__ == "__main__": print("Inside main block")
The first print will always show up, but the second one only shows up when the file is run directly.
基本上就這些。 It's a simple concept but super powerful once you understand how and why to use it.
以上是如何使用if __name__ ==' __ -main __”:構(gòu)造腳本執(zhí)行?的詳細(xì)內(nèi)容。更多資訊請關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

熱AI工具

Undress AI Tool
免費(fèi)脫衣圖片

Undresser.AI Undress
人工智慧驅(qū)動的應(yīng)用程序,用於創(chuàng)建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費(fèi)的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費(fèi)的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強(qiáng)大的PHP整合開發(fā)環(huán)境

Dreamweaver CS6
視覺化網(wǎng)頁開發(fā)工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

用戶語音輸入通過前端JavaScript的MediaRecorderAPI捕獲並發(fā)送至PHP後端;2.PHP將音頻保存為臨時文件後調(diào)用STTAPI(如Google或百度語音識別)轉(zhuǎn)換為文本;3.PHP將文本發(fā)送至AI服務(wù)(如OpenAIGPT)獲取智能回復(fù);4.PHP再調(diào)用TTSAPI(如百度或Google語音合成)將回復(fù)轉(zhuǎn)為語音文件;5.PHP將語音文件流式返回前端播放,完成交互。整個流程由PHP主導(dǎo)數(shù)據(jù)流轉(zhuǎn)與錯誤處理,確保各環(huán)節(jié)無縫銜接。

要實現(xiàn)PHP結(jié)合AI進(jìn)行文本糾錯與語法優(yōu)化,需按以下步驟操作:1.選擇適合的AI模型或API,如百度、騰訊API或開源NLP庫;2.通過PHP的curl或Guzzle調(diào)用API並處理返回結(jié)果;3.在應(yīng)用中展示糾錯信息並允許用戶選擇是否採納;4.使用php-l和PHP_CodeSniffer進(jìn)行語法檢測與代碼優(yōu)化;5.持續(xù)收集反饋並更新模型或規(guī)則以提升效果。選擇AIAPI時應(yīng)重點評估準(zhǔn)確率、響應(yīng)速度、價格及對PHP的支持。代碼優(yōu)化應(yīng)遵循PSR規(guī)範(fàn)、合理使用緩存、避免循環(huán)查詢、定期審查代碼,並藉助X

使用Seaborn的jointplot可快速可視化兩個變量間的關(guān)係及各自分佈;2.基礎(chǔ)散點圖通過sns.jointplot(data=tips,x="total_bill",y="tip",kind="scatter")實現(xiàn),中心為散點圖,上下和右側(cè)顯示直方圖;3.添加回歸線和密度信息可用kind="reg",並結(jié)合marginal_kws設(shè)置邊緣圖樣式;4.數(shù)據(jù)量大時推薦kind="hex",用

要將AI情感計算技術(shù)融入PHP應(yīng)用,核心是利用雲(yún)服務(wù)AIAPI(如Google、AWS、Azure)進(jìn)行情感分析,通過HTTP請求發(fā)送文本並解析返回的JSON結(jié)果,將情感數(shù)據(jù)存入數(shù)據(jù)庫,從而實現(xiàn)用戶反饋的自動化處理與數(shù)據(jù)洞察。具體步驟包括:1.選擇適合的AI情感分析API,綜合考慮準(zhǔn)確性、成本、語言支持和集成複雜度;2.使用Guzzle或curl發(fā)送請求,存儲情感分?jǐn)?shù)、標(biāo)籤及強(qiáng)度等信息;3.構(gòu)建可視化儀錶盤,支持優(yōu)先級排序、趨勢分析、產(chǎn)品迭代方向和用戶細(xì)分;4.應(yīng)對技術(shù)挑戰(zhàn),如API調(diào)用限制、數(shù)

字符串列表可用join()方法合併,如''.join(words)得到"HelloworldfromPython";2.數(shù)字列表需先用map(str,numbers)或[str(x)forxinnumbers]轉(zhuǎn)為字符串後才能join;3.任意類型列表可直接用str()轉(zhuǎn)換為帶括號和引號的字符串,適用於調(diào)試;4.自定義格式可用生成器表達(dá)式結(jié)合join()實現(xiàn),如'|'.join(f"[{item}]"foriteminitems)輸出"[a]|[

pandas.melt()用於將寬格式數(shù)據(jù)轉(zhuǎn)為長格式,答案是通過指定id_vars保留標(biāo)識列、value_vars選擇需融化的列、var_name和value_name定義新列名,1.id_vars='Name'表示Name列不變,2.value_vars=['Math','English','Science']指定要融化的列,3.var_name='Subject'設(shè)置原列名的新列名,4.value_name='Score'設(shè)置原值的新列名,最終生成包含Name、Subject和Score三列

pythoncanbeoptimizedFormized-formemory-boundoperationsbyreducingOverHeadThroughGenerator,有效dattratsures,andManagingObjectLifetimes.first,useGeneratorSInsteadoFlistSteadoflistSteadoFocessLargedAtasetSoneItematatime,desceedingingLoadeGingloadInterveringerverneDraineNterveingerverneDraineNterveInterveIntMory.second.second.second.second,Choos,Choos

安裝pyodbc:使用pipinstallpyodbc命令安裝庫;2.連接SQLServer:通過pyodbc.connect()方法,使用包含DRIVER、SERVER、DATABASE、UID/PWD或Trusted_Connection的連接字符串,分別支持SQL身份驗證或Windows身份驗證;3.查看已安裝驅(qū)動:運(yùn)行pyodbc.drivers()並篩選含'SQLServer'的驅(qū)動名,確保使用如'ODBCDriver17forSQLServer'等正確驅(qū)動名稱;4.連接字符串關(guān)鍵參數(shù)
