Python Interpreter

Introduction

  • To start the Python interpreter type python to the shell.

Argument Passing

  • The script name and additional arguments are passed with the variable sys.argv which is a list of strings.

Hello World with main

#!/usr/bin/python
 
# import modules used here -- sys is a very standard one
import sys
 
# Gather our code in a main() function
def main():
  print 'Hello there', sys.argv[1]
  # Command line args are in sys.argv[1], sys.argv[2] ..
  # sys.argv[0] is the script name itself and can be ignored
 
# Standard boilerplate to call the main() function to begin
# the program.
if __name__ == '__main__':
  main()

Interactive Mode

  • Interactive mode is when commands are read from a terminal.

Executable Python Scripts

  • Python scripts can be made directly executables by adding the following line #! /usr/bin/env python and making the file executable.

Import Path

Python looks in several places when you try to import a module. Specifically, it looks in all the directories defined in sys.path.

>>> import sys                
>>> sys.path                   
['', '/usr/local/lib/python2.2', '/usr/local/lib/python2.2/plat-linux2', 
'/usr/local/lib/python2.2/lib-dynload', '/usr/local/lib/python2.2/site-packages', 
'/usr/local/lib/python2.2/site-packages/PIL', '/usr/local/lib/python2.2/site-packages/piddle']
>>> sys                       
<module 'sys' (built-in)>
>>> sys.path.append('/my/new/path')
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.