Skip to content Skip to sidebar Skip to footer

Auto Executable Python File Without Opening From Terminal?

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 spec

Solution 1:

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 pythonprint"Hello World"

Solution 2:

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.

Solution 3:

http://supervisord.org is better choice.

Solution 4:

Have you placed this at the beginning of the file:

#!/usr/bin/python

?

Solution 5:

As others have said, you need put the "shebang" at the start of the file, to say which interpreter to use to execute the file.

As mentioned in the above link, the most portable way is to use the env command (instead of a fixed path to python) - put this as the first line in the file:

#!/usr/bin/env python

The shell will look in $PATH for your python, rather than looking for /usr/local/bin/python then failing. This means it will work if Python is installed in a non-standard location.

For example:

$ cat example.py
print"Test"
$ file example.py # it is treated as an ASCII file
example.py: ASCII text
$ chmod +x example.py
$ ./example.py # when executed, it defaults to being executed as a shell script
./example.py: line 1: print: command not found

Now, if I add the "shebang" line...

$ cat example.py#!/usr/bin/env python
print "Test"
$ file example.py # it is recognised as a Python script
example.py: a python script text executable
$ ./example.py # and executes correctly
Test

Post a Comment for "Auto Executable Python File Without Opening From Terminal?"