Running some simple Python scripts
Now we will look at writing a Python script in a file and executing it. For this we will use IDLE as it will provide syntax highlighting on the code. However, any text editor (for example, LeafPad, GEdit, nano, vim) can be used to write the Python files.
- First open IDLE and select New Window from the File menu, as shown in the following screenshot. This will open a new text editor window which will allow you to write and edit the script files.
- Now type the following code into the editor. This is a simple script that imports the
time
module and prints a string containing the current time to the terminal.import time print "The current time is: " + time.ctime()
Note
Keep in mind that the indentation level in Python is very important as this defines the scope that a line of code fits into. This will become clearer later on in the book when we start writing more complex codes.
- Save the file as
time.py
in the home directory by selecting Save from the File menu.Now that the script is saved, we can execute it using the Python executable at the command line.
- Open a terminal and enter the following command to execute the Python script:
python time.py
This will give the following output to the terminal:
One small improvement that could be made to this process is to include a shebang in the Python script that will tell the shell what to use to execute the script. This way we do not have to explicitly include the Python command when we run the script.
- Go back to the Python script in IDLE and add the following line as the very first line in the file:
#!/usr/bin/env python
- Next, we need to give execute permissions to the file in order to execute it directly (that is, without calling the Python executable first). This is done using the following command in the terminal:
chmod a+x time.py
- Now we are able to execute the script using the following command:
./time.py
This gives the following output on the terminal: