Create Python script executable

Suppose I have a Python script that I want to run by executing outside the command line by simply double-clicking it in the file explorer. When I double-click the .py file, a red command line appears and then disappears. What do I need to write to a file to include this?

I will be interested in the answer for both Windows and Linux, please!

+1
source share
3 answers

On Linux, you will need to make the .py executable

 chmod 750 mypyprog.py 

add the correct shebang to the first line to make the shell or file explorer know the correct interpreter

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

If you want to view the results before closing the shell window, it is useful to use the staller at the end (as shown in MackM):

 input('Press any key...') 

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

Windows does not know about shebangs. You will need to associate the .py extension with the Python interpreter, as described in the documentation . For this, the python interpreter should not be in PATH , because the full path can be specified here.

+1
source

Your script is running, and when it is completed, it will be closed. To see the results, you need to add something to stop it. Try adding this as the last line in the script:

 staller = intput("Press ENTER to close") 
0
source

I'm sure the right 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 that everything under the if statement occurs when it is opened from the outside (not when it is imported, because the " name " doesnt == " main " at that time)

To start it, simply double-click it. and BOOM starts up.

I don't have enough linux knowledge to confirm that it works on Linux, but it definitely works on Windows. Does anyone else confirm this?

0
source

Source: https://habr.com/ru/post/1262764/


All Articles