Python脚本不适用于双击

2022-01-18 00:00:00 python python-2.7 windows windows-7

问题描述

我有一个非常基本的问题,但我无法在旧答案中找到解决方案.当我双击 python 脚本时,我可以看到一个提示闪烁,但没有任何反应.如果我用 IDLE 打开相同的脚本并运行它,一切正常.为了确保脚本没有正确执行,我制作了一个这样的测试脚本:

I have a very basic problem, but I cannot find a solution in older answers. When I double click on a python script, I can see a prompt flashing but nothing happens. If I open the same script with IDLE and run it, everything works fine. To be sure the script was not executing propoerly, I made a test script like this:

def main():
   files = open('test.txt','a')
   files.write('this is a test')

如果通过空闲启动,简单脚本会写入文件,但如果我双击它,则不会发生任何事情.我尝试使用 .py 和 pyw 扩展名以及不止一台(Windows)电脑.我将python文件夹添加到路径中无济于事.

The simple script write the file if launched thru idle, but nothing happens if if I double click it. I tried with both .py and pyw extension and in more than one (windows) pc. I added the python folder to the path with no avail.

谢谢!


解决方案

确保脚本包含这段代码:

Make sure that the script includes this snippet of code:

if __name__ == "__main__":
    # call your code here
    main()

这是从命令行运行的脚本的执行入口点,例如 C/C++/Java/C# 中的 main() 函数.在 this 帖子中了解更多信息.

That's the execution entry point for a script running from the command line, like the main() function in C/C++/Java/C#. Read more about it in this post.

另外,不要忘记显而易见的 - 为脚本提供正确的执行权限,确保 python.exe 命令在 %PATH% 中可用环境变量等.

Also, don't forget the obvious - give the right execution permissions to the script, make sure that the python.exe command is available in the %PATH% environment variable, and so on.

相关文章