Reputation: 262
when you run a python script, you have to do
python3 filename
Is there something you can write in the python file to make it so that you dont have to say python3 before running it. I tried the #!/ line, but when I do:
./filename
it says permission denied. Is specifying the interpreter name when running the program mandatory?
Upvotes: 0
Views: 2601
Reputation: 2749
At the top of your python file, you'll want to add the path to the Python3 binary. This is commonly referred to as a "hashbang" or "shebang". It tells your shell how to interpret or run your file (without it, if you tried ./<python-file>
, it would try to interpret it as bash
.
#!/path/to/python3
On my computer, it's
#!/usr/bin/python3
To determine the path where your python3
binary (or link) is located, run
$ which python3
Alternatively, it's better to use env
, as it will ensure the interpreter used is the first one on your environment's $PATH
.
#!/usr/bin/env python3
Note, you'll need to run
$ chmod a+x <python-file>
to change the mode to make it executable. The a
tells it to make it executable for all (user, group, and others), so if you do not want this, you can leave it out (as in, chmod +x <python-file>
).
To not have to run ./
before the executable, you'll want to set your PATH
as
export PATH=$PATH:.
in your .bashrc
or similar *rc
file for your shell. (export
makes the variable available to sub-processes.) Then you'll want to run
$ source ~/.bashrc
Upvotes: 6
Reputation: 1965
I'm guessing you are on a linux or unix bases operating system. Yes there is something you can do. Hopefully you are using the import os
and import sys
library for any interaction with terminal. Next you have to do a chmod
command on the file to make it executable
The command would be
chmod +x [python_file.py]
or usually (if not root)
sudo chmod +x [python_file.py]
Upvotes: 0