Introduction |
This handout introduces Python programming in the Eclipse Integrated
Development Environment (IDE).
It is presented partly as a tutorial and partly in a "cook book" style: read
the text and follow the instructions to gain some hands-on experience
operating this software, which we will use extensively when we write, test,
debug, and beautify our own programs.
Use the resulting screen shots (checking them against what appears on your
computer) to ensure that you are correctly following these instructions.
In the sections below you will learn how to
The Eclipse project itself resides on the Eclipse.org web page. If you have not already done so, check the second message (Install Course Sofware) on the Announcements link for instructions on how to install Java, Python, and Eclipse (and now to configure Eclipse to run Python). It is an excellent idea to create a shortcut to Eclipse on the desktop, and once you have created an Eclipse workspace, a shortcut to it on the desktop. |
Starting and Stopping Eclipse |
We start Eclipse by double-clicking (a shortcut to) its icon, which is
commonly referred to as the Death Star (from the Star Wars movies).
The instructions for downloading/installing Eclipe include creating this shortcut; for lab machines, you must select Start | All Programs | Python and then double-click Eclipse to start Eclipse. While it is loading, Eclipse displays a splash window like the following.
After loading, Eclipse next displays the Workspace Launcher window. If this is the first time that we have started Eclipse, this window will display a suggested workspace typed in the Workspace pull-down box, as shown below. If we examine this pull-down box, there will be no other items in it.
The form of the suggested workspace is C:\Users\username\eclipse-workspace, where username appears above as pattis. On subsequent statups, the contents of the pull-down box will default to the last workspace that we used. It is possible to create/use multiple workspaces: the (10) most recently used ones will appear as items in the Workspace pull-down box, with the most recent workspace that we used visible at the top. This information is stored in the eclipse folder (created when Eclipse was installed), in the file configuration\.settings\org.eclipse.ui.ide.prefs (which is a text file that we can read and even edit). If we use just one workspace (recommended), we can put a check in the checkbox Use this as the default and do not ask again, to avoid this window's prompt altogether. Or, we can leave this box unchecked (recommended), at the small cost of having to click the Launch button in this window every time that we start Eclipse; on the positive side, whenever we start Eclipse we will be reminded of the folder that it is using for our workspace, which is useful if we need to know the workspace's name but forget which folder we are using as the workspace. It is an excellent idea to create a shortcut on the desktop to this standard Eclipse workspace. Go ahead now and click the Launch button to select the default work space. The progress bar on the bottom of the splash screen progresses to the end (should take under a minute), at which point the splash window will disappear and Eclipse should appear in the following form (although its window will be bigger on our screen). |
To stop Eclipse, we can either select File | Exit from the left-most
pull-down menu, or more simply just click the standard terminate window
button (X) in the upper-righthand corner.
If the latter, Eclipse will prompt for confirmation of termination with the
following window.
Here too, we can put a check in the Remember my decsion checkbox: doing so says to terminate in the future without prompting for confirmation. Or, we can leave this box unchecked (recommended), at the cost of having to click the OK button in this window every time that we stop Eclipse by clicking the terminate window button; on the positive side, we won't accidentally terminate Eclipse, because we need to confirm the termination. If we ever put a check in one of these "do not prompt again" checkboxes, but later want to restore these prompts, we can do it as follows. Once Eclipse appears on the screen, select Window | Preferences. Then disclose General (click its disclosre icon) and Startup and Shutdown (ditto) and then click on the Workspaces entry. We should ultimately see the following window (I am running this on my own computer, where my username is pattis).
We can check or uncheck the Prompt for workspace on startup box for our preference (recommended to leave this box checked), then click Apply and Close (or just Apply to see/set more preferences). Now click on Startup and Shutdow entry. You should see the following window.
We can check or uncheck the Confirm exit when closing last window box for our preference (recommended to leave this box checked), then click Apply and Close (or just Apply to see/set more preferences). Practice starting and stopping Eclipse, setting these prompt/confirm preferences as described above, and observing their behavior. After starting Eclipse, change the size of its main window, and note that when you stop and then restart it, the window will be the same size: Eclipse remembers the size of this window. In fact, once we start using Eclipse for real programming, whenever it starts it will appear exactly as it appeared when we last stopped it (same size, same geometry, same files open, etc). Therefore, it is simple to resume working in exactly the same context that we were in when we lat stopped Eclipse. While we are examining preferences, let's illustrate one more that is useful. Select Window | Preferences | PyDev | Editor | Auto Imports and uncheck the Do auto import? checkbox (illustrated below) and then click Apply and Close (or just Apply to see/set more preferences).
Doing so is especially important for Mac users, relating to our automatic grading program, which I run on my PC. |
Eclipse Nomenclature |
This section contains a terse description of Eclipse using highlighted
technical terms to describe its basic layout and operation.
Start becoming familar with these terms now; we will repeatedly use them during
the course, so we will become very familiar with them.
Because Eclipse is an industrial-strength tool, and we are using it in
an academic setting (an early programming course), we will focus on only its
simpler aspects.
The most important terms that we will discuss and use are workbench,
workspace, perspective, view, and toolbar.
Workbench/Workspace: These two terms are closely connected, to the point of having the same prefix: work. The workbench (or more accurately, the workbench window -see the window below) is the Eclipse interface to a workspace. The workspace is a folder that comprises a collection of files/subfolders that store the workspace's preferences (how the workbench window appears on the screen and how it displays/manipulates it contents) and projects (collections of related programming resources -primarily Python modules, but also data files). We interact with a workspace -view and manipulate its preferences and projects- through a workbench window. One of the primary ways we interact with projects in Eclipse is by editing their Python modules resources whilerunning/debugging/beautifying scripts. Preferences specify how a workbench window displays a workspace; projects specify the software that we can develop using the workbench window. In the section above, we started Eclipse and created a new, "empty" workspace; actually, it is not really empty: it stores all the standard preferences for the workbench window (stored in a folder named .metadata), but no projects yet. Then, the workbench window displayed this "empty" workspace. The workspace also records whether each project it contains is open or closed for use (for more details, see the section on Closing Workspaces). Finally a workspace stores preferences that apply to all its projects, and also apply to the workbench displaying the workspace. Eclipse is general: we can have any number of workbench windows open, each referring to a unique workspace. For simplicity, we will always use just one workbench window, and it will always refer to the same workspace. In fact, in the following discussion we often will say Eclipse when we mean a workbench window referring to our standard workspace. Below is an example of Eclipse using all the standard preferences, with labels affixed to many of it interesting features. It shows the "Demo" project that we are developing. The rest of the this section will examine other technical terms explaining its layout and operation. |
Perspective: At any given time, Eclipse displays one perspective
of the many that it can display.
Each different perspective is suited to one specific programming task.
The perspective shown above in Eclipse is the PyDev perspective,
which we use to develop Python modules (write/run/edit them).
Notice that the PyDev perspective appears depressed (it is active)
towards the top-right of the workbench.
It is followed by another icon, indicating the Debug perspective,
which we use to debug Python modules (find/correct errors in them).
We can switch to any perspective by clicking its icon; click the Debug
perspective and you will see its views (discussed below; many are the same);
then click the PyDev perspective to return to its views.
If we want the names of the perspectives to appear in the icon, we can right-click any icon and chose Show Text as follows
and these perspective icons would appear as
View: Each perspective contains a variety of views that allow us to view, navigate, and edit information about a project. So, views are not just for looking: we can use views to change information too. A view may appear as a single tab, or it may be one of many tabs in a tabbed window, containing many views, of which only one is active at a time- the top one. The PyDev perspective contains a variety of standard views illustrated above. Going clockwise from the top left,
Because these views are related, some information is propagated into multiple views: e.g., the red indicators that there are syntax errors in the code. When such errors appear/disappear in/from one window, they often simultaneously appear/disappear in/from others. Toolbar: The workbench toolbar appears under the menu bar that includes the drop-down menus labeled File, Edit, Refactoring, etc. The toolbar's buttons here act as short cuts for common operations in a perspective; we can also invoke these operations with the pull-down menus, but clicking these buttons is faster. The picture above labels the Make New, Debug, and Run/Rerun buttons, which are the most useful. The buttons on the toolbar change when we change the perspective. We can customize toolbars within a perspective, but we will not cover this topic here. Generally, we can manipulate the perspective and views (in a perspective) in a few interesting ways. Perspectives:
View:
|
Running the Python Interpreter |
In this section we will discuss how to run the Python Interpreter in Eclipse.
We run the interpreter to experiment easily with small amounts of Python code.
As beginners, we can easily perform experiments with the Python Interpreter to
help us learn simple Python language features: as more experienced
programmers, we can easily investigate more complicated language features and
libraries, while writing programs without leaving Eclipse.
We will take both roles as the quarter progresses, so it is important to know
how to access and use the Python Interpreter in Eclipse.
The Python Interpreter runs in a Console view.
When we start Eclipse we should see one Console view;
if we don't, we can select
the Window | Show View command illustrated in the previous section to
create a console tab.
Once we see a Console view, click it, then click the Open Console control
icon
The following pop-up menu will appear, with the first (Console for currently active editor) radio button pushed (as is shown below).
Click OK. The following will appear in the Console view (which appears every time we start the Python Interpreter).
We can type Python code at the green triple chevron prompt (>>>); when we press the ↵ key (aka Enter), the Python Interpreter will run our code, print its result, and prompt us again. This is know as REPL: Read (a command or expression), Execute/Evaluate it, Print the result, and Loop back to do it over again. Enter the Python code that appears in blue below, and verify that the Python Interpreter prints the information that appears in black.
If we enter a line with an error (e.g., misspell sqrt as sqr) the Python Interpreter will display a red error message: there is no sqr function in the math module. Instead of retyping this line correctly, we can press the ↑ (up arrow) key located on the numeric keypad (on the right of the keyboard) under 8 (make sure NumLock is off). This causes the Python Interpreter to redisplay the previous line that we typed, and we can now edit this line: e.g., by using the ← (left arrow) key located on the numeric keypad (on the right of the keyboard) under 4, to move the cursor left to the spot where we forgot to type the t, and type the t. Then we can press the End key located on the numeric keypad (on the right of the keyboard) under 1 to move the cursor to the end of the line and finally press ↵.
Alternatively, we can press the PgUp button but only when the cursor is at the beginning of the last >>> prompt and summon a Command history scrollable window, in which we can select any command we typed previously and re-execute it by clicking and and then clicking OK or double-clicking the command.
If we type characters in the bottom text field, the main Note that when we are editing a line in the Python Interpreter, we can also use the Home key to move the cursor to the start of a line, the → key to move the cursor right, the Backspace key to remove the character before the cursor and the Del key to remove the character after the cursor. In this way it we can easily correct any code we mistype in the interpreter. By experimenting with the interpreter, typing correct and incorrect commands -and fixing the incorrect ones- we can become proficient in using the interpreter.
We can fill the Eclipse window with the Console by double-clicking its tab or
by clicking the Maximimze icon |
We can return it to its original size by double-clicking its tab again, or by
clicking the midimize/restore icon ![]()
Finally we can click the triangle to the right of the Choose Active Console icon
When we have multiple active Consoles, we can click any line here to
select viewing that Console.
We can also click the |
Starting a New Programming Project |
In this section we will discuss how to start a new programming project,
and how to manipulate the perspectives and views on the workbench window
displaying that project.
In the next few sections we will learn what we need to know to develop programs
in a project: how to write and edit modules; how to run modules as
scripts; and how to find and fix syntax and execution errors in modules.
Start Eclipse as described above, which should look as follows. |
If your Workbench doesn't look exactly like this one, try to use the commands
covered earlier in this handout to get it too look exactly the same.
For example, you might have to open/close views, make the PyDev
perspective active, change the perspective icons to include text, etc.
To start a new project, click the down-arrow that is directly to the right of
the New icon (
Eclipse will display the following window.
In this window, I have started creating a new project folder. I have typed in the project name Demo. Eclipse has automatically filled in the Directory textbox with the name of the workspace folder it is using (because the Use default checkbox is checked), followed by the project name that I typed. When we are done entering all the information (typing the project's name, and ensuring that all the radio buttons and puldown menus are corect, specially selecting Grammar Version that is the default (Same as intepreter), we click Finish. Eclipse will create a folder with the name Demo in its workspace folder; when we create modules (files ending in .py; see below) for this project, they will be created in this Demo folder. Eclipse will update its workbench to show Demo project in its PyDev Package Explorer view; we can disclose the project to see it contents (when we create modules, they will appear here). Here is what the PyDev Package Explorer view looks like, with a disclosed project.
Note that if we misspell the project name, we can right-click it and choose the Rename option.
To create a new module (containing the script that we are going to run) inside
this project, first right-click the Demo project (which should appear
as
We can also right-click the Demo project and then click the New pull down triange and select PyDev Module. Eclipse will then display the following window.
In this window I have started creating a new module. Eclipse has automatically filled in the Source Folder textbox with the name of the project folder (Demo) so the module file (Script.py) will be put there. If you do not see anything in the Source Folder textbox the best thing to do is to Cancel the module, then go back and select the Demo project and start creating a new module again (or you can type /Demo into this textbox). Eclipse starts by putting the cursor in the Package textbox. Leave that textbox empty and instead select the Name textbox. Type the module name, Script, there (Eclipse will add the .py to the name of any Python module). Finally, click Finish. Eclipse will now show the following window.
It should automatically highlight <Empty>: if it does, then click OK; if it doesn't, either double-click <Empty> or single-click it and then click OK. Eclipse will create a file named Script.py in the project folder of the Demo project and displays the contents of this file in an editor tab with then name Script. Initially, this module contains just a comment about when the module was created and by whom. Eclipse will update its workbench to look as follows. Notice that Eclipse will automatically put some information into any file it creates (even ones whose template is <Empty>). |
Note that if we misspell the module name, we can right-click it and choose the
Rename option.
Before continuing to the next section (how to write and edit Python code), we
will briefly explore how to manipulate windows and views, to customize them.
|
Editing a Module/Script File |
We edit Python modules in tabs in the Editor view, mostly using standard
text editing commands.
Click the Edit pull-down menu for a list of commands and their
keyboard shorcuts.
Also click the Source pull-down menu for additional commands involving
commenting, reformatting, and generating/organizing the code in a module.
Whenever we create a new module, or double click any module in the PyDev Package Explorer, Eclipse will add a view/tab for editing that module in the editor window (if such a view is not already present). Sometimes project include more than one file. Within an editor window, we can manipulate views/tabs for different files as s described above. To add a second Editor view/tab for a module -so that we can view two parts of it simultaneously- we select the tab to duplicate and select the Window | Editor | Toggle Split Editor command (choosing a Horizontal or Vertical split). If we choose a horizontal split as follows
a second view (not a tab with a name) will appear in the Editor view under the Script tab. |
.
If we issue this toggle command again on the Script tab, Eclipse
will merge the two views back into one
Eclipse should be configured so that the files we edit show their line numbers;
as programmers, we will find multiple uses for these numbers.
If you do not see these number, right-click in the left margin in any Editor
view (e.g., under the Python module
Multi-digit line numbers will be right-aligned. When Eclipse is configured to show line numbers, it will continue to show line number each time that we start Eclipse (unless we explicitly reconfigure it). Here is the most important information about the Eclipse editor:
Here is the Python code for a complete Python module that I typed into Eclipse: both the Editor and Outline views are present, because Eclipse changes the Outline view as I type code into the Editor view. For now, read the information below to learn how to interpret the contents of the Editor and Outline views. At the end of this section you will be asked to duplicate this code in Eclipse. And in the next section, we will learn how to run this code. |
.
Note the annotations indicating
To save the changed contents of an Editor view to its file, right-click in the view and select Save; note that this option will not be selectable if the file has not changed: if the file-change indicator is absent. Another way to issues this command is just by typing ctrl/s on the keyboard when this tab is selected. After issuing this command, the file is updated to contain all the information currently in the tab for this module. If instead we right-clicked the view and selected the Revert File command, the view would would be restored to the file's contents when it was last saved. So, use Save and Revert File carefully: we will be using Save much more than Revert File, and we can always select the Edit | Undo Typing command (or just press ctrl/z to undo any changes (and selecting this command multiple times undoes multiple changes; if we go too far with ctrl/z, we can press ctrl/y to redo undone commands). If we issued the Save command in the window above, it would be updated and appear as follows.
Note the disappearance of the asterisk (the file-changed indicator) and the purple change bars. Often, if we forget to save a file, and perform some othe operation in Eclipse -such as running a script- Eclipse will ask us whether to save the file(s) first. In the Eclipse editor, whenever we type an opening delimiter -e.g., a parenthesis, brace, bracket, or quotation mark- the editor automatically supplies the matching closing delimeter, and then repositions the cursor between the two so, that we can easily type the delimited entity. Related to this behavior, if the cursor is followed by a closing delimiter, and we type that same closing delimiter, the Editor just moves the cursor past it. This editor behavior can be a little confusing, until we get used to it; but for writing programs, this is useful behavior. Likewise, whenever we double-click directly after an opening delimiter (except for the quotation mark), the editor automatically highlights all information between that delimiter and its matching closing delimiter. Below I double-clicked just to the right of the first opening parenthesis on line 10.
This operation -matching opening and closing delimiters- is often useful when we are debugging (removing errors from) our programs: errors related to correctly matching opening to closing delimiters.
We can hide any mult-line code (here the top string and cheer_up
function/method) from the Editor view by clicking its disclosure
circle.
Generally throughout Eclipse clicking on a + means disclose the elided
information; clicking on a - means hide the disclosed information.
In the Editor view below, we have hidden the cheer_up function/method:
notice how it shows the header of the method, but not its body, instead
showing
In fact, if we hover over a disclosure circle that is eliding information, the cursor will change to a hand (not shown below) and Eclipse will temporarily display the elided information in a yellow box, while keeping it elided in the Editor view (so we can peek at it).
If we hover over a name in an Editor view, Eclipse shows us something interesting about that name: its definition.
If we click on a name in the Editor view, Eclipse selects that name as a token and shows us other places in that Editor window where this same name appears, by putting the name in a yellow background.
Likewise, in complicated modules, with many names, we can use the Outline view to rapidly examine selected names in the module. By clicking an entry in the Outline view, Eclipse shows us where it was defined in the Editor view (its defintion is outlined in blue) and where it is used (outlined in yellow).
Finally, whenever we start typing a token, Eclipse displays possible
completions for that token based on Python keywords.
Until it recognizes a correct token, Eclipse marks the code with a syntax
error icon (
We can continue typing the token, or double-click one of the keywords to have Eclipse complete the token. If we press ↵ Eclipse will complete the token with the highlighted completion (and we can use the ↑ and ↓ keys to scroll through the possible completions before using ↵ to make our selection). Don't be distracted by this mechanism; it is probably best to just keep typing your code and ignore the completions. Pressing Shift/↵ tells Eclipse to ignore word complettion for this word. In addition if we press the ctrl/space command when Eclipse present us with keyword completions, it will present us with other "useful" code that might go here. Below I have highlighted the pow selection, and Eclipse provides me with information about it in yellow on the right. I can scroll through or select one of these entries as described above.
Again, it is probably best to ignore these other completions for now. There is a delicate balance beetween what information you should supply and what information Eclipse should provide. Now it is time to go back and enter into Eclipse all the code illustrated in this section, and reread and practice doing all the operations discussed. Remember to type the code carefully, with letters in their correct case, proper punctuation, and proper spacing. Watch carefully what happens when you pres ↵ on lines that do or don't end with a colon (and what the backspace key does on indented lines). Once you are done entering this code, you can go to the next section and learn about executing/runnning it. |
Running a Module/Script |
A module of Python code that is runnable (sometimes called "launchable") is
called a script; other modules contain code that acts as a library of names,
and these aren't runnable.
To run a script that we are editing, click the Run icon:
![]() The first time we run a Python project, Eclipse will display the following Run As pop-up window.
Click on Python Run and then click OK. Python will save the file for this module and then run its script; if there is no Console view in which to run the script. Eclipse will create a new one.
If the Console view ever disappears, we can always bring it back by selecting Window | Show View | Console. We have already seen one Console view in connection with running the Python Interpreter. In fact, if we already have a Console view that shows the Python Interpreter running, it is replaced by a Console view that shows the the script running; the Python Interpreter is still running, and we will see how to bring it back into the Console view at the end of this section (also see the end of the Running the Pyton Interpreter section above).When run this way, the Python script above displays the following. |
First, notice that information entered by the user appears in a green font;
information displayed by the computer appears in a black font.
Also notice that the line below the Console view shows that the
script has run to completion: it is terminated.
The interaction appears in the contents of the Console view: if it
does note fit entirely in this view, its contents can be scrolled -both
vertically and horizontally.
Of course we change the relative sizes of the Editor and Console
views, or can double-click the Console view to maximize it.
There are two useful tool buttons to the right of the Console view. Immediately to the right is the Terminate button, a faded-red square that stops a running script (it is faded here, because it cannot be selected: the script has already terminated). The next one is the Remove Launch button, a grey X, which clears the contents of the Console; Eclipse does this automatically, if a terminated script is rerun (so only the latest run will appear in the Console). Try clicking the Remove Launch button: it will clear the console; then click the Run button again. The Console view below shows this script in the middle of running; it is waiting for the user to enter a number.
Here the line below the Console view does NOT indicate that the script has terminated. So, the Terminate button is bright red, but now the Remove Launch button is Grey: a script must be terminated before it can be removed. Pres the Terminate button to terminate the script. The Console view now shows as
Run the script again.
If we don't enter a number for this run, and rerun the same script without
terminating the first, Eclipse will do it in another console (remembering
both but displaying only the later).
Suppose we do enter the number 5 here so the second run terminates.
We can see both consoles by clicking the triangle to the right of the Choose
Active Console icon |
Here it shows the second launch has terminated, but the first launch is still
running.
We can remove the current (second) launch and/or just select the first launch
to show it in the Console view (and continue running it).
When we rerun the same script, Eclipse will reuse the Console
view with this terminated script, erasing its original contents first.
You should experiment with runing, terminating, and removing runs/launches,
using the buttons mentioned above and the arrow to the right of the
Choose Active Console icon.
Finally let's briefly examine the most useful buttons (labeled below) on the Console toolbar. They are useful when we are running many scripts (including the Python Intepreter) and need to switch among them or terminate/remove them all. Note that sometimes some of these buttons are missing or gray, in which case Eclipse believes that they would be useless in the current context. |
The most important thing to say here is that we need to terminate a launch before we can remove it from the Console view. There are two ways to do each.
The biggest problems with Console views is that whenever we run a script (or start a Python Interpreter) it takes over the Console. If we need to see other launches, we must use the black triangle to the right of the Display Selected Console button to select one, or click the button itself to cycle through the various launches. It might be simpler to have multiple Console view tabs, but Eclipse doesn't support this features. Practice all these operations until you are comfortable using the Console view while running and rerunning programs, and using the Python Interpreter. |
Finding and Fixing Syntax and Execution Errors |
The process of debugging involves first finding and correcting syntax errors,
so the program can run, and then correcting execution errors, so that the
program will run correctly (produce the correct results).
This section discusses how to debug both syntax errors and execution errors,
using the standard PyDev perspective; a later handout discusses how to
use the Debug perspective to help debug more complicated execution
errors.
The universal color for a syntax error indicator in Eclipse is red; the
universal indicator for a syntax error in Eclipse is a red backgound:
typically Editor tabs show a red circle containing a white X
(e.g., Often a single syntax error results in multiple red boxes appearing in multiple views. Likewise, the universal color for a warning indicator in Eclipse is yellow. You must stop and fix an error, but you just need to be cautious with a warning (just like road signs). We will discuss when to pay close attention to warnings later in the quarter. Note that if we click the Project pull-down menu, the item Build Automatically should be checked: if it isn't, click it, and the next time you click this pull-down menu it should be checked (clicking toggles it). Eclipse tries hard to spot syntax errors while we are typing/editing our modules, to help us spot them and fix them immediately. In the following sequence we will type in parts of a script file named Errors.py to observe how we interact with Eclipse to fix syntax errors. For example, if we starting import prompt, while we are still typing the word prompt Eclipse indicates a syntax error on that line and makes a suggestion. |
When we hover over any error icon, Eclipse shows us information about the error; the information, coming from Python's perspective, may or may not be useful to us understanding the problem. Don't be misled.
When we correct the spelling, Eclipse indicates a syntax warning on that line. When we hover over this warning icon, we see the following.
Here Eclipse warns us that although we have imported a module correctly, we haven't used it anywhere: of course, since we have just started to type a program, this doesn't concern us. So in this case we can ignore the warning; it will disappear once we write code that uses prompt. If we hover over the word Prompt we will see the following information.
When we use prompt in the next line, but use it incorrectly (there is no for_inp function defined in this module; there is a for_int function), Eclipse removes the warning on line 1 but shows us an error on line 3.
Note the the red line on the upper right is not on the line with the error. By being at the top, it indicates just that an early line contains an error. In a file with hundreds of lines, this area on the right indicates the relative line position of the error. We can click on these red line and the Editor view will show us the line with the error. When we hover over the error icon, Eclipse shows us the following information.
When we correct the spelling of the function name to for_int in that line, but write a call to the print function incorrectly on line 5 (it includes a comma before the string 'Answer is '), Eclipse indicates a syntax error on that line.
Sometimes Eclipse will still mark line 3 as an error. In such cases, it might take a few seconds for Eclipse to re-analyze the file; we can also save the file (ctrl/s or right-click in the window and select save), which often forces Python to re-analyze it. When we remove this comma, Eclipse shows no more syntax errors in our module. Notice the names prompt and x in the Outline view: these are the two name we define in this script. Now that this script has no syntax errors, we can run it. When we do, we get the following interaction in the Console view. |
Python executed the import statement and the assignment to x correctly
(calling the for_int function in the prompt module; the user
typed the value 3 to the prompt), but when it tried to execute line 5
it found an execution error (which raised an exception).
It
So, there are two kinds of errors in programming. Eclipse can detect syntax errors before it runs a script and execution errors after it runs a script. We will learn much more about avoiding, interpreting, and fixing syntax and execution errors throughout the quarter. There a many ways to fix this error; below we edit the script so that it calls the function str explictly, with x as its argument. Editing the file and clicking the Run icon leads to the following interaction. |
The interactions among editing, saving, and (re)running a script can sometimes be a bit subtle and confusing. Confusion arises especially concerning the synchonization of the files we are editing and Eclipse's reporting of syntax errors in various views. For one example, sometimes we type a few lines before Eclipse detects a syntax error on one of the lines (there can be a few seconds of lag). As another example, if we fix an error, its associated error indicators may disappear from some -but not all views; we must sometimes perform further operations, like saving the file to synchronize all these views. There is no substitute for using Eclipse repeated to better understand its operation: power and limitations. It is always an excellent idea, if you are confused, to save the file and wait a few seconds to see what syntax errors Eclipse detects. The following shows what Eclipse would display, if we had continued typing code without fixing the syntax errors. We can do this and come back to fix these errors later, but it is probably better to try to fix each syntax error as Eclipse discovers it (but not necessarily each warning, as we've seen some warnings go away by themself). Notice how errors show themselves in many of the views; also notice that there are three distinct red lines on the right, indicating three lines with errors at the top of the program. |
|
Advice for Debugging Syntax Errors |
Interpret syntax errors/warnings liberally.
|
Finishing a Project: Closing/Removing It |
As we have seen before, when we terminate Eclipse, it saves all the preferences
and projects that appear in our workbench.
When we restart Eclipse, it initializes itself in exactly the same state as
when it terminated.
Therefore, we can seemlessly start Eclipse, create/work on our projects, stop
it, restart it, and continue working on our projects just where we left off.
(this is not exactly true: any programs that were running when we stop Eclipse
are automatically terminated).
Now let us explore three options for finishing a project. We need to find out what happens to such projects both on our workbench and in our workspace: knowing the distinction between these terms is citical to understanding these three options. The simplest option is to just leave a finished project alone. It will continue to be present on our workbench and in our workspace; we can can undisclose the project so it appears as just one line (not showing any resources in the project). This is a safe option, although our workbench can become cluttered, and we might accidentally change a project that we meant to leave alone. Still, I recommend leaving projects elided to one line on your workbench; so, we will only briefly explore two other options: closing and deleting projects. Closing: First, we can just close the project by right-clicking the project name/folder an choosing Close Project in the menu (right below Refresh/F5).
Closed projects will still appear in the PyDev Package Explorer view in our workbench (and are still stored as folders in our workspace folder), but with appear with no disclosure triangle: we cannot examine, run, or modify our code in closed projects. Here is what a closed project looks like in the PyDev Package Explorer view.
One of the few operations that we can perform on a closed project is to reopen it: by right-clicking its name and then selecting Open Project (which replaces Close Project on the window above). Once this is done, we can explore the contents of the project again. So, if we are done with a project, we can close it (to avoid accidentally changing it) but reopen it later, if we need to examine/change it: closing is an operation that can be un-done. Note that we can always copy a project (or just its .py files) from the workspace to any other folder, say to back-up the information. It is always a good idea to back-up your work regularly, although Eclipse is a safe environemnt in which to work: most operations can be un-done. Another option we have is deleting a project from the workbench (not just closing it); we will discuss the two forms of deleteing next.
Deleting: Our second option is actually removing a project from our
workbench (and possibly the workspace too).
In this case, the project disappears altogether from our workbench (is not
visible in the PyDevPackage Explorer view), as if it were not there;
we have the option of leaving its project folder in the workspace (the
default), or truly deleting the project folder and all its contents.
We delete a project by right-clicking its name and then selecting
(
If we leave the Delete project contents on disk (cannot be undone) checkbox unchecked, Eclipse removes the project from its workbench, but the project folder and the files containing all its resources remain intact in the workspace. In such a case, we can leave this information where it is, or copy/move it elsewhere; at a later time, if we want to recreate the project, it will be easy to do if we have not deleted the project folder and its resources (see the next section for information about how to do this). But, if we check the Delete project contents on disk (cannot be undone) checkbox, then Eclipse will not only remove the project from its workbench, but also will delete the project folder and all its resourcess: .py files and any others. Obviously this latter choice is very dangerous, and I recommend NEVER putting a check in this checkbox, which always defaults to being unchecked. If need be, and after we are done with the safer Delete operation, we can use a Windows file explorer explicitly to delete the project folder ourself; or better yet, archive it by moving it to any other directory on our computer. In any case, at this point Eclipse does not know the project exists, whether or not it is still in our workspace folder. The project will not appear on the workbench. |
Starting an Existing (Old) Programming Project
I often distribute projects in this form |
We have already seen in detail how to start a new project in Eclipse.
When started, these projects contain no modules (no .py files).
We have also seen how to create modules in these projects, edit their files,
and run their scripts.
In this section, we will learn how to start a project using an
existing/old project folder that likely already contains modules.
For example, we might download from the web a folder that contains a one or more modules and then run one of these modules as a script. My Sample Programs link (in the index of the course page) leads to a repository of such project folders. Frequently during in the quarter, I will ask you to download programming project folders that contain code that I want you to examine, or in the case of assignments, some starter code in modules that I have written. The easiest way to create a project from an existing/old project folder is first to copy (or move) that folder into the workspace folder (if it is not already there). In fact, as we just learned, if we delete a project from a workspace, but do not delete its contents, the project folder remains in the workspace. By deleting the Demo project above, and not deleting its contents, we now have an empty workbench, but the Demo project folder is still in our workspace. To start a project from an existing/old project folder in the workspace, first ensure that there are no .project nor .pydevproject files in that folder: if there are, delete them. If you you are unable to see files starting with . (called hidden file), try the following links to instruct your operating system to show them. Or try googling your operating system name and "show hidden files".Then click the down-arrow that is directly to the right of the New icon ( ![]()
Eclipse will display the following window.
When we type Demo, the name of a project folder already in the workspace, the line under PyDev Project will say Project location contains existing Python file. The creatre project will include them. The, by clicking Finish, Eclipse creates a project on the workbench from the folder in the workspace, including all the resources that it contains. You can disclose the project in the workbench to see its resources (files). We must be careful to spell the name of the existing project folder correctly; if we misspell the name, Eclipse will create a new project folder, rather than use the old one that already exists. If we do misspell the old project folder's name, and Eclipse creates a new project folder for us with this wrong name, we can delete this new project (including its contents, to completely delete it from the workspace), and then repeat these operations but spelling the project folder name correctly. Also, if the following error message appears when you are trying to create an old project
Terminate the current pop-up windows, remove the .project and .pydevproject files from that project folder, and then try creating this old project again. |