使Python脚本可执行

时间:2014-09-25 17:59:45

标签: python

假设我有一个Python脚本,我希望通过在命令行外执行来运行,只需在文件资源管理器中双击即可。当我现在双击.py文件时,会短暂显示黑色命令行框,然后消失。我需要在文件中写什么来启用它?

我对Windows和Linux机器的答案感兴趣!

3 个答案:

答案 0 :(得分:1)

在Linux下,您必须使.py文件可执行文件

chmod 750 mypyprog.py

在第一行添加适当的shebang以使shell或文件资源管理器知道正确的解释器

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

如果要在shell窗口关闭之前查看结果,最后的staller(如MackM所示)很有用:

input('Press any key...')

正如我们从评论中看到的那样,您已经掌握了第1步和第2步,因此3将成为您的朋友。

Windows不了解shebangs。您必须按照in the documentation所述将.py扩展名与Python解释器相关联。 python解释器不必位于PATH中,因为可以在那里指定完整路径。

答案 1 :(得分:0)

您的脚本正在正在运行,一旦完成,它就会关闭。要查看结果,您需要添加一些东西来阻止它。尝试将其添加为脚本中的最后一行:

staller = intput("Press ENTER to close")

答案 2 :(得分:0)

我很确定正确的方法是

#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语句中的任何内容在从外部打开时都会发生(而不是在导入时,因为&#34; 名称&#34;不会==&#34 ; 主要&#34;当时)

要运行它,只需双击它即可。和BOOM它运行。

我没有足够的Linux熟悉程度来确认它是如何在Linux上运行的,但它肯定适用于Windows。其他人都证实了这一点吗?