Python auto-executable file without opening from terminal?
Sorry if this is not the right site (superuser probably), but I am trying to make my python.py executable so I can click on it and it automatically does its job without telling it to open in the terminal at that prompt by default and I already have "chmod + x" for its rights.
Clarification:
- I want to launch it by clicking on it, not through the terminal (I meant when I said "you can click on it and it does its thing automatically")
- There is already a shebang line
- When I click on it right now, it tells me if you want to open it in a text file, terminal - can I make it always open in terminal by default, or is it just an odd selection query?
source to share
First, select the file extension you want for the files you want to have this behavior. pyw is probably a good choice.
Name your file, which in your file browser associates this file type with python. In GNOME, you will open the Properties window, go to the Open With tab and enter python as a custom command.
Now, here's the important part: this little dialog you asked about what you want to do with the file is that it is marked as executable. Remove the executable bit with chmod -x. Now when you double-click on it, it will simply open with the appropriate program.
Of course, if you want to run it from the command line, now you will need to run it with python explicitly, since it is not marked executable. The shebang line doesn't matter anymore, but I would leave it anyway in case someone else marks it as executable and expects it to fire.
source to share
As others have said, you need to put a "shebang" at the beginning of the file to tell you which interpreter to use to execute the file.
As mentioned in the link above, the most portable way is to use a command env
(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 yours python
, instead of searching /usr/local/bin/python
and 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
source to share