简体   繁体   English

通过双击使 Python 脚本可执行

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

Suppose I have a Python script, that I want to run by executing outside of the command line, just by double-clicking it in the File Explorer.假设我有一个 Python 脚本,我想通过在命令行之外执行来运行它,只需在文件资源管理器中双击它即可。 When I double-click a .py file now, a black command-line box appears briefly and then disappears.当我现在双击一个.py文件时,一个黑色的命令行框会短暂出现然后消失。 What do I need to write in the file to enable this?我需要在文件中写什么来启用它?

I'd be interested in the answer for both Windows and Linux.我会对 Windows 和 Linux 的答案感兴趣。

Under Linux, you will have to make the .py file executable在 Linux 下,您必须使.py文件可执行

chmod 750 mypyprog.py

add the proper shebang in the first line to make the shell or file explorer know the right interpreter在第一行添加适当的 shebang 以使 shell 或文件资源管理器知道正确的解释器

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

If you want to review the results before the shell window is closing, a staller at the end (as shown by MackM) is useful:如果您想在 shell 窗口关闭之前查看结果,最后的staller(如 MackM 所示)很有用:

input('Press any key...')

As we see from the comments, you already mastered steps 1 and 2, so 3 will be your friend.正如我们从评论中看到的,您已经掌握了第 1 步和第 2 步,因此 3 将成为您的朋友。

Windows does not know about shebangs. Windows 不知道 shebangs。 You will have to associate the .py extension with the Python interpreter as described in the documentation .您必须按照文档中的说明.py扩展名与 Python 解释器相关联。 The python interpreter does not have to be in the PATH for this because the full path can be specified there.为此,python 解释器不必在PATH中,因为可以在此处指定完整路径。

Your script is running, and when it's done, it's closing.您的脚本正在运行,完成后,它正在关闭。 To see the results, you need to add something to stall it.要查看结果,您需要添加一些东西来停止它。 Try adding this as the last line in your script:尝试将其添加为脚本的最后一行:

staller = intput("Press ENTER to close")

I'm pretty sure the proper way to do this would be something like:我很确定这样做的正确方法是:

#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")

This makes it so anything that is under the if statement happens when opening it from outside (not when you import it, because __name__ doesn't equal "__main__" at that time).这使得 if 语句下的任何事情在从外部打开它时都会发生(而不是在你导入它时,因为__name__不等于"__main__" )。

To run it, simply double-click it, and BOOM it runs.要运行它,只需双击它,然后 BOOM 就会运行。

I don't have enough Linux familiarity to confirm this is how it works on Linux, but it definitely works on Windows.我没有足够的 Linux 熟悉度来确认这就是它在 Linux 上的工作方式,但它绝对可以在 Windows 上工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM