[Tutor] Running .py files in shell

Kevin Rapley kevin at digikev.co.uk
Wed Jul 28 08:39:23 CEST 2010

>> I am running Mac OSX v10.6.4 Snow Leopard
>> I am running Python 2.6.1
> In general get the MacPython distributions of Python etc, they usually
> install easier (ie from the GUI) than the "Unix" based versions.
Okay, thanks. I will look into that.
>> 1. How do I execute .py files in the command line shell? I have my
>> files in /Users/Kevin/python-exercises/ and am opening python in
>> shell from that directory
> There are numerous ways, especially in MacOS.
> The simplest way is to put a "shebang" line at the top of your script
> and then make them executable:
> $ cat>  myscript.py
What is the significance of this and how do I use it? I guess this is a 
command to add in to Shell, however when I use this I get the following 

 >>> cat > tryme1.py
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
NameError: name 'cat' is not defined
> #! /bin/env python
With my configuration, I am guessing I need to change this snippet to:

#! /opt/local/Library/Frameworks/Python.framework/Versions/2.6/bin python
> # the above line must be the first line in your file and tells the
> # shell where to find python
> # rest of your code follows.....
> Then use chmod +x to make it executable
> $ chmod +x myscript.py
When I try to run this with one of my files I get the following error:

 >>> chmod +x tryme1.py
   File "<stdin>", line 1
     chmod +x tryme1.py
SyntaxError: invalid syntax
> Now you can run it:
> $ myscript.py
> Alternatively you can just call python explicitly:
> $ python myscript.py
I get a syntax error doing this too:

 >>> python tryme1.py
   File "<stdin>", line 1
     python tryme1.py
SyntaxError: invalid syntax

More information about the Tutor mailing list