Running Python script from a command prompt

Create the file in a text editor (I’m using Emacs).  For example, here’s a text file I called testfile.py:

#! /usr/bin/env python

print "Hello, world!"

Now we need to make the file executable.  In the command line, type:

$ chmod a+x testfile.py

Then you should be able to run it like this:

$ testfile.py

In order for this to work (running the script directly from the command line), the directory containing the script must be defined in the env PATH variable (to check path type echo $PATH).  Since this is *not* usually the case, ie, the directory you’re working in is defined as a PATH variable, the program can be run like this: ./testfile.py.  Doing this tells the interpreter to look in the current directory (./).

I used these links to help me with this stuff:

How do I make a Python script executable on unix?

Executable Python scripts

As well as Beginning Python.

Leave a Reply

Your email address will not be published. Required fields are marked *