User:MyOwnLittlWorld/Python/Python: Non-Interactive (Script) Mode

From Wikibooks, open books for an open world
Jump to: navigation, search
  • What is script mode?
  • Why is it useful?
  • What are Python scripts?

Prerequisites[edit]

Making and Changing Directories:

Opening Terminal/Commandline Windows:

Running Python in Script Mode[edit]

1. Find your text editor

  • Windows: "Start" -> "Accessories" -> "Notepad"
  • Mac OS X: Open TextEdit, then go to the menubar and click "Format" -> "Make Plain Text"
  • Linux: Run "gedit", "kedit", "mousepad", "nano", "vim", "emacs", or the like.

2. In your text editor, type the following (don't just copy and paste, that's lazy, typing reinforces the learning):

#!/usr/bin/python
 
print "We are the knights who say, Ni!"

3. Save the file as "hello.py", under some obvious directory that you won't mind saving a lot of python files in.

4. Now, run it:

  • Open up your command line/terminal again, change to the directory where you just saved your python file, and type:
python hello.py

5. Viola! Python printed "We are the knights who say, Ni!" to your screen! You now know how to create and execute python scripts.

Exercises[edit]

  • Modify the hello.py program to say hello to a historical political leader (or to Ada Lovelace).
  • Change the program so that after the greeting, it demands, "You must cut down the mightiest tree in the forest with.... A HERRING!".

Solutions

Running Scripts in Interactive Mode[edit]

If you want to run scripts in interactive mode, you can start python with "-i". This can be very useful for debugging and prototyping:

python -i hello.py