Reputation: 2038
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!
Upvotes: 0
Views: 115
Reputation: 55469
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.
Upvotes: 0
Reputation: 168616
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":.
Upvotes: 2