Python 脚本不适用于双击 [英] Python script doesn't work with double click
问题描述
我有一个非常基本的问题,但我在旧答案中找不到解决方案.当我双击一个 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)PC.我将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()
函数.在这篇博文中阅读更多相关信息.
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.
这篇关于Python 脚本不适用于双击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!