Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto executable python file without opening from terminal?

Tags:

python

linux

Sorry if this is on the wrong site ( maybe superuser ) but I'm trying to make my python.py file executable so I can click on it and it automatically does its thing, without me specifying it to open in the terminal by that default prompt, and I already have 'chmod +x' for its permissions.

Clarification:

  • I want to run it by clicking on it, not through the terminal ( I meant that when I said 'can click on it and it automatically does its thing ' )
  • Already have a shebang line
  • When I click it right now, it prompts me with do you want to open it in a text file, terminal - can I make it always default to opening in the terminal or is this just an oddball request?
like image 545
meder omuraliev Avatar asked Oct 28 '25 03:10

meder omuraliev


2 Answers

On the first line in your python file, add this:

#!/usr/bin/env python

So if you have:

print "Hello World"

You should then have:

#!/usr/bin/env python
print "Hello World"
like image 187
unlobito Avatar answered Oct 29 '25 18:10

unlobito


First, pick a file extension you want for files you want to have this behavior. pyw is probably a good choice.

Name your file that, and in your file browser associate that file type with python. In GNOME, you'd open its Properties window, go to the Open With tab, and enter python as a custom command.

Now here's the important part: That little dialog you've been getting asking you what you'd like to do with the file is because it is marked as executable. Remove the executable bit with chmod -x. Now when you double click it, it will simply be opened with the associated program.

Of course, if you want to run it from the command line, you'll now have to start it with python explicitly since it isn't marked executable. The shebang line doesn't matter anymore, but I'd leave it in anyway in case someone else marks it executable and expects it to work.

like image 21
kwatford Avatar answered Oct 29 '25 16:10

kwatford



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!