簡體   English   中英

通過雙擊使 Python 腳本可執行

[英]Making a Python script executable by double-clicking

假設我有一個 Python 腳本,我想通過在命令行之外執行來運行它,只需在文件資源管理器中雙擊它即可。 當我現在雙擊一個.py文件時,一個黑色的命令行框會短暫出現然后消失。 我需要在文件中寫什么來啟用它?

我會對 Windows 和 Linux 的答案感興趣。

在 Linux 下,您必須使.py文件可執行

chmod 750 mypyprog.py

在第一行添加適當的 shebang 以使 shell 或文件資源管理器知道正確的解釋器

#!/usr/bin/env python3
print('Meow :3')             # <- replace this by payload

如果您想在 shell 窗口關閉之前查看結果,最后的staller(如 MackM 所示)很有用:

input('Press any key...')

正如我們從評論中看到的,您已經掌握了第 1 步和第 2 步,因此 3 將成為您的朋友。

Windows 不知道 shebangs。 您必須按照文檔中的說明.py擴展名與 Python 解釋器相關聯。 為此,python 解釋器不必在PATH中,因為可以在此處指定完整路徑。

您的腳本正在運行,完成后,它正在關閉。 要查看結果,您需要添加一些東西來停止它。 嘗試將其添加為腳本的最后一行:

staller = intput("Press ENTER to close")

我很確定這樣做的正確方法是:

#somefile.py

def some_definition_you_want_to_run():
    print("This will print, when double clicking somefile.py")

#and then at the bottom of your .py do this
if __name__ == "__main__":
     some_definition_you_want_to_run()
     #next line is optional if you dont "believe" it actually ran 
     #input("Press enter to continue")

這使得 if 語句下的任何事情在從外部打開它時都會發生(而不是在你導入它時,因為__name__不等於"__main__" )。

要運行它,只需雙擊它,然后 BOOM 就會運行。

我沒有足夠的 Linux 熟悉度來確認這就是它在 Linux 上的工作方式,但它絕對可以在 Windows 上工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM