22

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!

Michiel Buddingh
  • 5,783
  • 1
  • 21
  • 32
Steve Gattuso
  • 7,644
  • 10
  • 44
  • 59

5 Answers5

49

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
  • 174,939
  • 50
  • 355
  • 478
  • 3
    after much pain and near-death experiences, I suggest to use the specific python version you develop for #!/usr/bin/env python. (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 Sep 21 '09 at 17:31
  • the shebang should point to whatever distribution of python you expect the script to run on; often this ships with the script itself. – anon01 Oct 28 '21 at 17:29
15

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)

Community
  • 1
  • 1
Michiel Buddingh
  • 5,783
  • 1
  • 21
  • 32
2

Shebang?

#!/usr/bin/env python

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

rlazo
  • 635
  • 4
  • 14
1

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
  • 366
  • 1
  • 2
  • 8
0

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
  • 725
  • 6
  • 6