繁体   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