views:

227

answers:

5

Hey everyone,

I'm writing a pretty basic application in python (it's only one file at the moment). My question is how do I get it so the python script is able to be run in /usr/bin without the .py extension?

For example, instead of running

python htswap.py args

from the directory where it currently is, I want to be able to cd to any directory and do

htswap args

Thanks in advance!

+8  A: 

The first line of the file should be

#!/usr/bin/env python

You should remove the .py extension, and make the file executable, using

chmod ugo+x htswap

EDIT: Thomas points out correctly that such scripts should be placed in /usr/local/bin rather than in /usr/bin. Please upvote his answer (at the expense of mine, perhaps. Seven upvotes (as we speak) for this kind of stuff is ridiculous)

Michiel Buddingh'
Yep that was it, I did this earlier and for some reason it didn't work, turns out I forgot the ! in the shebang
Vestonian
+2  A: 

Shebang?

#!/usr/bin/env python

Put that at the beginning of your file and you're set

rlazo
Oh baby when she moves...
windfinder
+1  A: 

add #!/usr/bin/env python to the very top of htswap.py and rename htswap.py to htswap then do a command: chmod +x htswap to make htswap executable.

b3rx
+13  A: 

Simply strip off the .py extension by renaming the file. Then, you have to put the following line at the top of your file:

#!/usr/bin/env python

env is a little program that sets up the environment so that the right python interpreter is executed.

You also have to make your file executable, with the command

chmod a+x htswap

And dump it into /usr/local/bin. This is cleaner than /usr/bin, because the contents of that directory are usually managed by the operating system.

Thomas
after much pain and near-death experiences, I suggest to use the specific python version you develop for #!/usr/bin/env python<version-major>.<version-minor> (e.g. python2.4) instead. Better to have control of the python version is running the executable (at least for the cases I experienced, YMMV)
Stefano Borini
A: 

I see in the official Python tutorials, http://docs.python.org/tutorial/index.html, that

#! /usr/bin/env python

is used just as the answers above suggest. Note that you can also use the following

#!/usr/bin/python

This is the style you'll see for in shell scripts, like bash scripts. For example

#!/bin/bash

Seeing that the official tuts go with the first option that is probably your best bet. Consistency in code is something to strive for!

rand_acs