How to Run a Python Script

Like this post? Rate it:
27765

If you cannot run or execute a python script, there is no point in being a programmer. I mean, the ultimate goal of a developer is to write scripts that are executable and actionable. You see, whenever you run a python script, the IDE converts the syntax into instructions that the computer can understand and act on. Technically, this is doable in two ways.

  1. Using the interactive python shell or
  2. Calling the interpreter using a shebang line.

Under which environments can I run a python script?

Typically, python developers write stand-alone scripts that can only be executed under certain environments. These scripts are then saved with a “.py” extension so that the operating system can identify them as python files. Once the interpreter is invoked, it identifies the script, reads it and then interprets it accordingly. However, the way python scripts are executed on Linux is different from the way they are “Run” on Windows or Mac. Confusing? Well, if you are a greenhorn in the game of coding, the whole idea can become confounding. Fortunately, we’ve got you covered. In this post, we are going to iron things out by showing you the difference in these systems and also teach you how to run a python script on Windows, Mac, and UNIX platforms. Read on!

How to run a python script on command line

Python is one of the simplest and most executable programming languages used by greenhorns as they make baby steps into the world of coding. And though a variety of applications can be used to create and execute python scripts, it is a little-known fact that windows command line can run these same programs regardless of the development method or tool used to create them. Technically, a command line prompt can be effortlessly launched from your computer’s start menu. Under most windows versions, the menu selection process is: Start ‣ Programs ‣ Accessories ‣ Command Prompt. Another option is entering 'cmd' in the menu search box. After successfully launching the command, the following window should appear.

C :\>

Depending on where your system files are stored, the letter that appears might be different. For instance, you might get something like:

D:\YourName\Projects\Python>

Once this command prompt window has been launched, you will be on your way to running python scripts. However, for python scripts to be executable, they have to be processed by a python interpreter. The role of this interpreter is to read the script, compile it into bytecodes, execute the bytecodes and subsequently run the program.

But how do you navigate the interpreter on the command prompt so that it can process your script?

Well, first and foremost, ensure that your command prompt recognizes the word “python” as a command to launch the interpreter. If you already have a command prompt window open, key in the command python and press enter.

C:\Users\YourName> python

If successfully done, you should get the following result depending on the version of python you are using.

Python 3.3.0 (v3.3.0:bd8afb90ebf2, Sep 29 2012, 10:55:48) [MSC v.1600 32 bit (Intel)] on win32

Type "help", "copyright", "credits" or "license" for more information.

>>>

This indicates that you have launched the interpreter in “interactive mode”. From now on, you can key in python commands, expressions, and scripts interactively and have them run as you wait. This interactive mode is one of Python’s most iconic feature. Most programmers use it as a convenient and highly programmable calculator. You can try it out by typing a few commands of your choice and see what happens.

>>> print("Hello")

Hello

>>> "Hello"*3

'HelloHelloHello'

When it’s time to end your interactive session, press the “control” key, enter “z” and press “Enter” to return to your windows command prompt window.

If your computer has a start menu as Start ‣ Programs ‣ Python 3.3 ‣ Python (command line) which opens up a command prompt >>> on a new window, it will also disappear after pressing the Ctrl and Z buttons. The thing is, your system only runs one “python” command which stops all windows after ending your interactive session with the interpreter.

Possible errors and how to solve them

If the python command gives you the following error messages instead of launching the interpreter prompt >>>

'python' is not recognized as an internal or external command, operable program or batch file.

Bad command or filename

double check if your computer knows where to find the interpreter. To achieve this, you have to modify the list of directories (PATH) where windows gets programs before launching them. Go ahead and add python’s entire installation directory to the path of every command window. If you are not sure where you installed python, the following command will help you find out.

dir C:\py*

The most typical location should look like C:\Python33. If that’s not your case, you might have to search the entire disk. However, you can avoid it by using the search button. Type “python.exe” in the search box. If it is installed in the following directory, C:\Python33 (which is normally the default setting at the time of installation) make sure that when you execute the following command

c:\Python33\python

It launches the interpreter as shown at the beginning of this guide. If the search results indicate that the installation directory is not part of the system path, add it so that it can be possible to launch the interpreter after running the python command. Once the directory is verified, launching the python interpreter should not be a problem again. Do not also forget that you will need to press the control and Z keys to terminate the session. Once you have verified that the

How to run a python script on Windows

  1. First and foremost, create a folder where you are going to be storing your python scripts. It has to be saved in a format that windows can understand that it is a python file. For instance, you can have C:\pythonscripts as your folder name. After the folder is ready, go ahead and save your script in it. For example, hello.py.
  2. From the start menu, click “Run” the type cmd on the search box. This command is going to open the windows terminal.
  3. If your python directory is not saved in a location that windows can find it, type cd \pythonscripts to modify the PATH of your folder then press enter.
  4. Type in the name of your python script and press enter to run your script. In my case, I am going to type hello.py because it is the name of my script.
  5. If any of these steps fail to work, double check and ensure that your computer’s PATH contains the python directory so that windows can know where to get it from.

How to run a python script on Mac

  1. Like on windows, create a dedicated folder where you will be storing your python programs. For instance, you can decide to call it pythonprograms. Be sure to store it under your home folder which contains your Music, movies pictures, and other documents. Save your python script in this folder and make sure it is saved in such a way that Mac understands that it a python file. For this tutorial, we are going to be saving our script as hello.py
  2. After saving your script, launch the applications folder, open the utility folder and select the terminal program.
  3. Key in the name of the folder that contains the python script and press enter. In our case, it is going to be cd pythonprograms. This command will change the directory of the folder so that the OS can locate and execute it.
  4. Type in the name of the script to run it. For this tutorial, it is going to be python ./hello.py

NB: Most Mac computers come preinstalled with python 2 and 3. if this is the case, you should always use python3 hello.py.

How to run a python script on Linux

  1. Create a dedicated folder which is going to store your python scripts and programs. The format should be in such a way that your Linux OS can identify the file as s python file. An ideal name for the folder can be cd ~/pythonpractice. After creating the folder, save your script in that folder. Ours will be named hello.py.
  2. Launch the terminal program. Under KDE, click on the main menu then select “Run command”. This is going to open up the console. In GNOME launch the main menu and select the applications folder then open it up. Go ahead and open up the accessories folder and click on “terminal”.
  3. Change the directory of the folder containing your scripts by typing in the following command cd ~/pythonpractice. This ensures that the Linux OS can find the script when executing it.
  4. Unlike in other operating systems, you have to make it executable in Linux. This is achieved by executing the following command chmod a+x hello.py.
  5. After making sure that it is executable, type in the name of the script to run. In our case, we are going to type python ./hello.py

NB: If version 2.61 and 3.0 are both installed in your computer, you should always run python3 hello.py.

How to run a python script on Linux (advanced)

  1. Like in the previous scenarios, you still have to create a dedicated folder that is going to house your python script. The folder name should be in this format ~/pythonpractice.
  2. Launch your text editor and create a new script called hello.py, it should contain only two lines of syntax. If you want, you can copy paste it.
    	#! /usr/bin/python
    	print('Hello, world!')
    	
  3. Save this script in the ~/pythonpractice folder you previously created.
  4. Launch the terminal program. Under KDE, click on the main menu then select “Run command”. This is going to open up the console. In GNOME launch the main menu and select the applications folder then open it up. Go ahead and open up the accessories folder and click on terminal.
  5. Change the directory of the folder containing your scripts by typing in the following command cd ~/pythonpractice. This ensures that the Linux OS can find the script when executing it.
  6. Unlike in other operating systems, you have to make it executable in Linux. This is achieved by executing the following command chmod a+x hello.py.
  7. Key in ./hello.py to run your script.
  8. Alternatively, you can key in this command ln -s hello.py /usr/bin/hello to create a link between /usr/bin and hello.py under hello then execute by using the command hello.

This advanced process should only be used to execute completely compiled programs. If you regularly use your script, it will be ideal if you can store it in your home directory and link it using /usr/bin. And if you want to play around with the commands, it will be fun to invoke mkdir ~/.local/bin then transfer your scripts to this location. To make these scripts executable in a similar manner that /usr/bin does, key in this command $PATH = $PATH:~/local/bin

NB: file extensions are not necessary under UNIX file systems. In Linux, hello.py simply means what Hello.mp3 or hello means. Normally, the Linux OS uses the contents of a file to determine what type it is, unlike in windows and Mac where you have to specify file type by adding an extension.

How to run a python script in python shell

The python shell not only interprets commands line by line and executes them instantly, but also gives you the autonomy to run them over and over again whenever you wish to. It gives you the freedom to save your entire script in a python format, then run it on the python shell. But how?

STEP-1

Launch the IDLE editor. It should be available under the All Programs section in windows. After double-clicking on it, a python shell should appear as shown in the picture below.

STEP-2:

Select the file menu then click on “New file”

Simultaneously pressing the CTRL and N keys will also open an untitled and empty document editor as illustrated below. (Shortcut)

STEP-3

Write or paste your program on this editor window. If you have already saved yours, please jump to step 5.

STEP-4

After you’re done with your script or program, click on the file menu then select save. Make sure that the script is saved in a location that you can remember. You should get something like this after saving. The top section should show you where the document has been saved.

STEP-5

Launch a command window then navigate to the location where you have stored your file. In my case, I am going to type the following command.

cd c:\PythonSnippets

(Or)

I also have the alternative of using windows explorer to get my script. Press the shift button and right click to launch the open command window. You can then go ahead and open the folder containing the script.

STEP-6

On the command window/prompt that appears on your computer screen, key in the following command and press enter. This will depend on the way you have saved your script. In my case, I will have,

python AddTwoNumbers.py

Calling out the name of your script should execute your python script.

An alternative

Instead of following the whole process from the first to the last step, everything can be completed in step 3. On this Step, the script can be directly saved by pressing F5 on the editor, then it will run the program itself.

When using the live interpreter to run a python script, it is important to understand that understand that every command is read and integrated in real time. For instance, calculations will be solved immediately while loops will iterate immediately unless they are part of a function. For this reason, you have to be mentally prepared to use it. The python shell is popular with people who like executing their code interactively. However, if you want to use it to run your scripts, you have to call the Python executable or import it.

Anon
15:37
+1
Mistake under «How to run a python script on Mac»section:
«Save your python script in this folder and make sure it is saved in such a way that Linux understands that it a python file.»
Should correct «Linux» with «Mac».
18:54

Thank you, Anon. Fixed.

Write a comment

Loading...