1

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.

wovano
  • 4,543
  • 5
  • 22
  • 49
Karnivaurus
  • 22,823
  • 57
  • 147
  • 247
  • 1
    See also: http://stackoverflow.com/questions/20521456/python-scripts-stopped-running-on-double-click-in-windows – MackM Feb 23 '17 at 14:41

3 Answers3

2

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.

flaschbier
  • 3,910
  • 2
  • 24
  • 36
-1

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")
MackM
  • 2,906
  • 5
  • 31
  • 45
-1

Using something like this file that creates a file to prove it worked

#somefile.py
#!/usr/bin/env python3
def some_definition_you_want_to_run():
    """ This will run if python is on your path """
    print("This will print, when double clicking somefile.py")
    with open('lookforme.txt', 'w') as file:
        file.write('you found me!')
        

#and then at the bottom of your .py do this
if __name__ == "__main__":
     some_definition_you_want_to_run()

WINDOWS:

Python has to be on path, and when you see the icon it should look like a piece of paper with the python logo on it. If you double click it it should create the file.

LINUX

Same file as above. Run this also.

$ nano run.sh
# in Nano enter `python somefile.py`
$ chmod +x run.sh

I think at this point run.sh is double clickable on ubuntu as long as you are logged in as the user that made this file.

TehTris
  • 3,139
  • 1
  • 21
  • 33