Friday, April 11, 2008

Executing a Python Source Code File

Note:

filename means you must replace the text filename with the name of the file including extension that you are using.
C:\Python23 is an example; replace C:\Python23 with the actual drive letter and directory where your Python is installed.

Command Line

  • Open a Windows Console.
  • Navigate to the drive and working directory of your choice.
  • Enter one of the following commands to start the Python interpreter:

    • C:\Python23\python filename
      (The directory C:\Python23 is not in your PATH environment variable)
    • python filename
      (You have set your PATH variable such that the directory C:\Python23 is in your path)

Windows Explorer and File Associations

If standard Python file extensions like .py are associated with Python (the default for a standard Windows installation) then you can simply double-click a Python source file in Windows Explorer to run the script. There are 2 problems with this method:

  • The output will display briefly in a console window, then the window will immediately close. You need to remember to put a "pause" input prompt at the end of your script to keep the window open, usually something like the following (See Input & Output below):
raw_input("Press ENTER to continue...")
  • All Python scripts can easily be executed with a double-click by anyone curious about what the script does, including your unfinished and untested scripts. There are better ways (at least in my opinion) to make scripts executable:
    • Convert them to batch files with embedded Python script.
    • Move the script to a different folder and create a Windows shortcut to the script.

No comments: