1
votes

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 a Windows and Linux machine please!

3
are you one linux machine or windows? - salmanwahed
Well I use Windows mainly, but I'm interested for both cases! - Karnivaurus
When you double click a .py file, what happens? Does a black box appear and then disappear? - MackM
Yes -- a black command line window just pops up briefly! - Karnivaurus
You'll need to add the python.exe file to your window's path system/environment variable. - ScottO

3 Answers

1
votes

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

0
votes

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")
0
votes

Im 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" doesnt == "main" at that time)

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

I dont have enough linux familiarity to confirm this is how it works on linux, but it definitely works on windows. Anyone else confirm this?