简体   繁体   中英

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. When I double-click a .py file now, a black command-line box appears briefly and then disappears. What do I need to write in the file to enable this?

I'd be interested in the answer for both Windows and Linux.

Under Linux, you will have to make the .py file executable

chmod 750 mypyprog.py

add the proper shebang in the first line to make the shell or file explorer know the right interpreter

#!/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:

input('Press any key...')

As we see from the comments, you already mastered steps 1 and 2, so 3 will be your friend.

Windows does not know about shebangs. You will have to associate the .py extension with the Python interpreter as described in the documentation . The python interpreter does not have to be in the PATH for this because the full path can be specified there.

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).

To run it, simply double-click it, and BOOM it runs.

I don't have enough Linux familiarity to confirm this is how it works on Linux, but it definitely works on Windows.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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