7

I am not sure if I searched for the wrong terms, but I could not find much on this subject. I am on osx and I'd like to compile a commandline python script into a small commandline app, that I can put into usr/local/bin so I can call it from anywhere. Is there a straighforward way to do that?

Thanks

moka
  • 4,263
  • 2
  • 36
  • 63
  • 2
    that should be prety easy just put `#!/path/to/python` ( or `#!/usr/bin/env python`) at the start of you're script, then make it an executable using chmod ( `chmod +x path/to/script` ) you should then be able to call it – Poelinca Dorin Nov 25 '11 at 16:14
  • You want to be able to execute it like `my_script` instead of eg. `./my_script.py`? – Tadeck Nov 25 '11 at 16:15
  • I asked a bit similar question http://stackoverflow.com/questions/7976926/how-do-i-make-python-processes-run-with-correct-process-name. You would want to make that script executable. Cant help with the "compilation" part though: please tell us your intention. – Jesvin Jose Nov 25 '11 at 16:16
  • well I don't necessarily wan't to compile it, I just want to make it accessible fron anywhere.- I would prefer it if it would be accesible with my_script instead of ./my_script.py. Thanks! – moka Nov 25 '11 at 16:24

5 Answers5

6

The simplest way to do this is to rename your file from filename.py to filename and add this line to the top of the file.

#!/usr/bin/env python

You may also need to set the executable bit on the file, which may be set using chmod +x on the command line.

Andrew Marsh
  • 1,914
  • 13
  • 14
4

On Unix it works usually in the following way:

  1. Put #!/usr/bin/env python in the first line of your .py script.
  2. Add execution permissions to the file (using chmod).
  3. Execute the script from command line, eg. by providing ./my_script.py when in the same directory.

What else do you need?

Tadeck
  • 125,377
  • 26
  • 148
  • 197
2

A Python script is already a "command line app" that you can put anywhere.

Just set the first line of your script to be a proper shebang pointing to your Python interpreter For example:

#! /usr/bin/python

(Or wherever OS X puts its Python interpreter), set your script with the executble attributes, and put it on your bin folder

(it does not need to end in ".py" either)

jsbueno
  • 86,446
  • 9
  • 131
  • 182
0

you can write

#!/usr/bin/python 

in the very beginning of your script or write shell script that will lauch your script like

#!/bin/sh
python path_to_your_script/your_script.py
0

As almost everybody said, you can turn your script executable by adding the following line at the beginning of the script:

#!/usr/bin/env python

and setting it to be executable:

chmod +x script.py

Another alternative, is to convert your script into a native executable. For that, you may use Freeze or py2exe, depending on your target platform.

Quetzy Garcia
  • 1,810
  • 1
  • 22
  • 23