您在這裡

Python Programming on Macintosh

24 二月, 2015 - 15:32

In this appendix, we walk through a series of steps so you can run Python on Macintosh. Since Python is already included in the Macintosh Operating system, we need to learn how to edit Python files and run Python programs in the terminal window.

There approaches you can take to editing and running Python programs, and this is just one approach we have found to be very simple.

First, you need to install a programmer editor. You do not want to use TextEdit or Microsoft Word to edit Python programs. Programs must be in ”flat-text” files and so you need an editor that is good at editing text files. Our recommended editor for Macintosh is TextWrangler which can be downloaded and installed from:

http://www.barebones.com/products/TextWrangler/

To create a Python program, run from TextWrangler from your Applications folder.

Lets make our first Python program be:

print 'Hello Chuck'

Except that you should change it to be your name. Lets save the file in a folder on your Desktop named py4inf. It is best to keep your folder names short and not to have any spaces in your folder or file name. Once you have made the folder, save the file into Desktop\py4inf\prog1.py.

The run the Terminal program. The easiest way is to press the Spotlight icon (the magnifying glass) in the upper right of your screen and enter “terminal” and launch the application that comes up. You start in your “home directory”. You can see the current directory by typing the pwd command in the terminal window.

67-194-80-15:˜ csev$ pwd /Users/csev67-194-80-15:˜ csev$

We must be in the folder that contains your Python program to run the program. We user the cd command to move to a new folder and then the ls command to list the files in the folder.

67-194-80-15:˜ csev$ cd Desktop67-194-80-15:Desktop csev$ cd py4inf67-194-80-15:py4inf csev$ lsprog1.py67-194-80-15:py4inf csev$

To run your program, simply type the python command followed by the name of your file at the command prompt and press enter.

67-194-80-15:py4inf csev$ python prog1.pyHello Chuck67-194-80-15:py4inf csev$

You can edit the file in TextWrangler, save it and then switch back to the command line and execute the program again by typing the file name again at the command line prompt.

If you get confused in the command line window - just close it and start a new one.

Hint: You can also press the “up-arrow” in the command line to scroll back and run a previously entered command again.

You should also look in the preferences for TextWrangler and set it to expand tab characters to be four spaces. It will save you lots of effort looking for indentation errors.

You can also find further information on editing and running Python programs at www.py4inf.com.