I would like to run python files from terminal without having to use the command $ python. But I would still like to keep the ability of using '$ python to enter the python interpreter. For example if I had a file named 'foo.py', I can use $ foo.py rather than $ python foo.py to run the file.
How can I do this? Would I need to change the bash file or the paths? And is it possible to have both commands available, so I can use both $ foo.py and $ python foo.py?
I am using ubuntu 14.04 LTS and my terminal/shell uses a '.bashrc' file. I have multiple versions of python installed on my computer, but when running a python file I want the default version to be the latest version of 2.7.x. If what I am asking is not possible or not recommended, I want to at least shorten the command $ python to $ py.
Thank you very much for any help!
2 Answers 2
Yes you can do this.
1) Ensure that the first line in your file looks like this:
#!/usr/bin/env python
2) Ensure that your files have the execute permission bit set, like this:
$ chmod +x foo.py
3) Now, assuming that your $PATH environment variable is set correctly*, you can run foo.py either way:
$ foo.py
$ python foo.py
* By "correctly", I mean, "to include the directory where your python file lives." In the use case you describe, that probably means "to include the current directory". To do that, edit .bashrc. One possible line to put in .bashrc is: PATH="$PATH":.
7 Comments
import, for example. And the "way around that" is to say python foo.py.$ echo $PATH is /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games. Do you know if this path is set up correctly?$PATH does not include .. (Neither does mine, by the way. I hate having . in my $PATH.) So, you shold either add . to your $PATH, or invoke your program thus: ./foo.py.ls and secretly put it in a directory some where. Whenever I cd /my/friends/directory and typed ls, I'd get their program instead of the system one. In fact, my .bashrc is this: PATH="$HOME/bin:$PATH". That way, when my Python program evolves into something useful, I can copy it to $HOME/bin and make it always available to me, regardless of my current working directory.sharkbyte,
It's easy to insert '#!/usr/bin/env python' at the top of all your Python files. Just run this sed command in the directory where your Python files live:
sed -i '1 i\#! /usr/bin/env python\n' *.py
The -i option tells sed to do an in-place edit of the files, the 1 means operate only on line 1, and the i\ is the insert command. I put a \n at the end of the insertion text to make the modified file look nicer. :)
If you're paranoid of stuffing up, copy some files to an empty directory first & do a test run.
Also, you can tell sed to make a backup of each original file, eg:
sed -i.bak '1 i\#! /usr/bin/env python\n' *.py
for MS style, or
sed -i~ '1 i\#! /usr/bin/env python\n' *.py
for the usual Linux style.
Comments
Explore related questions
See similar questions with these tags.