Python
Executing a Script


return to main index



Introduction

It is often more convenient to execute (run) a python script by double-clicking than by opening a CMD window (Windows) or a terminal (OSX & Linux) and entering,

    python nameOfScript.py

This tutorial demonstrates how run a python script by double clicking on Windows, OSX and Linux. The python script is shown below.


Listing 1 (demo.py)


import inspect
import os.path
import os
  
fullpath = inspect.getframeinfo(inspect.currentframe()).filename
dirpath = os.path.dirname(os.path.abspath(fullpath))
scriptname = os.path.basename(fullpath)
  
print('----------------------------------------')
print('"%s" is located in "%s".' % (scriptname, dirpath))
print('The operating system is "%s".' % os.name)
print('----------------------------------------')

Part of the code is taken from this Stack Overflow page.


Windows

Create a .bat file and give it the same name as the python script, for example, demo.bat. Save the bat file in the same directory as the python script. The bat file should contain the following code.

    C:\python27\python demo.py
    pause

Double clicking the bat file will open a CMD window.



Figure 1


OSX

Create a file and give it the same name as the python script, for example, demo. Note the file does NOT have a file extension. Save the file in the same directory as the python script. The file should contain text similar to that shown below.

    # chmod +x /Users/malcolmkesson/run_py_script/demo
    python /Users/malcolmkesson/run_py_script/demo.py
    read

The file must be given "execute" permission. If the reader is using the Cutter text editor select the first line of text, excluding the "#" comment character, and use the keyboard shortcut Alt+e or Control+e. Cutter will run the selected text as if it had been entered into a terminal.

Double clicking file will open a terminal window.



Figure 2


Linux

Create a file and give it the same name as the python script, for example, demo. Note the file does NOT have a file extension. Save the file in the same directory as the python script. The file should contain text similar to that shown below.

    python demo.py
    read

Double clicking file will open a terminal window.



Figure 3





© 2002- Malcolm Kesson. All rights reserved.