Raspberry Pi - Run Python Script in the Terminal - The Robotics Back-End (2024)

Great, you’ve learned a bit of Python 3 with your Raspberry Pi and you might be wondering: how can you run a Python 3 script in the terminal?

For now you may have used only the Thonny Python IDE, or any other easy-to-use system to write Python programs. This is perfectly fine, especially to start learning. But after a certain point you’ll need to work with Python directly inside the terminal of your Raspberry Pi.

In this tutorial I’ll show you how to do that. Let’s get started!

Table of Contents

Check Python version on your Raspberry Pi

As you may now, Python 2 is not supported anymore since 2020. However, this doesn’t mean that Python 2 has disappeared, or that it can’t work! In many systems Python 2 is still present, and the first thing you want to check is if it’s still there.

If you have Python 2 and Python 3 installed on environment, then for the following you’ll want to make sure you only run scripts using Python 3, which is the newer and recommended version to use.

Open a terminal, and run:

You are learning how to use Raspberry Pi to build your own projects?

Check out Raspberry Pi For Beginners and learn step by step.

$ python --versionPython 2.7.16

If you’re using Raspberry Pi OS, you’ll probably have something similar. The version number can change a bit, but it’ll start with 2.x.

Now, run:

$ python3 --versionPython 3.7.3

So, you have to make the difference between the “python” command – Python 2 – and the “python3” command – Python 3.

If you just want to run Python 3 by default and not pay attention to the version anymore, you can add an alias in your bashrc. This will make sure that when you type “python”, “python3” will be executed instead. To do that simply run this command: echo "alias python=python3" >> ~/.bashrc.

Note: for the following of this tutorial I’ll still use the “python3” command.

Run Python code directly on the terminal

Before we even begin to write and execute complete files, you can just run any Python command you want directly on the terminal – in what we call a “Python shell”.

If you’ve used Thonny IDE before, you could use the shell panel to write + execute code directly, line by line. Well this is the same.

Open a terminal, and run “python3” without any argument.

$ python3Python 3.7.3 (default, 13:03:44) [GCC 8.3.0] on linuxType "help", "copyright", "credits" or "license" for more information.>>>

This is what you should get at the end : “>>>”.

This means that you’re in a Python shell, inside your “terminal shell”. Now, all the commands you’ll write will be interpreted as Python commands.

>>> print("Hello")Hello>>> a = 2>>> print(a)2>>> import os>>>

As you can see, we can even create variables and use them later.

Using the Python shell in the terminal is a great way to quickly test small features, for example:

  • if a module is correctly installed: running import module will give you an error if the module can’t be found.
  • to test small hardware components with the “RPi.GPIO” module. You can power on/off a LED directly from the Raspberry Pi terminal.
  • etc.

Now, how to quit this shell?

If you press CTRL+C you’ll get this:

>>> KeyboardInterrupt>>>

Python will catch the signal sent by CTRL+C and will throw a KeyboardInterrupt exception, which you can also catch in your code if you want to.

But the shell won’t be closed. To close the shell, you’ll have to execute the command “exit()” – with the parenthesis.

>>> exit()pi@raspberrypi:~ $

Note that when you exit the shell, all variable states and functions you’ve written inside the shell will be lost. So, only use the shell for quick tests, and when you want to create real programs, create your own Python scripts instead.

Create and run Python scripts on Raspberry Pi

If you’ve used the Thonny IDE (or any other IDE) before on the Raspberry Pi, you’ve seen that you just need to:

  1. Open the IDE and write Python code in the text editor.
  2. Save the script into a file thanks to the graphical interface.
  3. Execute the script by clicking on the “play” button.

Good news: you can do all those steps without even leaving the terminal on your Raspberry Pi!

>> Video version:

After watching the video, subscribe to the Robotics Back-End Youtube channel so you don’t miss the next tutorials!

Write a Python program inside the terminal

To do that, you’ll need to use a text editor.

On Raspberry Pi OS and most other operating systems, you can easily find and use the Nano text editor. When you open a file with Nano, no new window will be open. You’ll just write some text in the terminal, and then save the file if you want to. Another popular IDE for Raspberry Pi is Vim.

To create and write a new Python script with Nano:

  • Open a terminal.
  • Use nano filename.py on an existing file or just give a new file name (you can save it later).
  • Write your Python code.
  • Press CTRL+S to save the file.
  • press CTRL+X to exit Nano and come back to the terminal.

If you want to create a file first, before editing the text, use the “touch” command: touch filename.py. You can also modify a file name with “mv”: mv old_file_name.py new_file_name.py. And to remove a file: rm filename.py.

Note: when creating Python files in the terminal, it’s important to give them the extension “.py”, so you can differentiate them from other types of files.

Also, as a best practice, add #!/usr/bin/env python3 at the beginning of your Python scripts. This will make sure that any program running this script will know which interpreter (here Python 3) to use.

Well, as you can see, it’s fairly easy and quite convenient to use the terminal to write a Python script.

Run a Python script in the terminal of your Raspberry Pi

All right, now that you have a Python script saved into a file, it’s time to run it directly from the terminal.

Simply use “python3” + the name of the file: python3 filename.py. This will execute the script just like if you’d execute it inside an IDE.

Now, to stop/kill the script, you’ll have to press CTRL+C.

You’ll notice that when you press CTRL+C, you get a “KeyboardInterrupt” message. It’s an exception you can actually catch in your program. For example, after catching KeyboardInterrupt you could clean up some hardware pins or closing some open files, before exiting the program.

Also, a best practice is to make your script an executable. To do that, run “chmod +x” on the file: chmod +x filename.py. This way, you can directly run your script without using the “python3” command line tool: ./your_script_with_or_without_an_extension.

Manage Python packages with pip3

>> Video version:

If you create and run your Python scripts in the terminal, you’d also want to be able to manage Python modules from the terminal as well.

This is also quite easy thanks to the pip3 command line tool.

And here again, similar to what we’ve seen with “python” and “python3” commands, there are 2 variations for pip.

$ pip --versionpip 18.1 from /usr/lib/python2.7/dist-packages/pip (python 2.7)$ pip3 --versionpip 18.1 from /usr/lib/python3/dist-packages/pip (python 3.7)

If you get an error with pip3, it’s probably because you need to install it: sudo apt install python3-pip.

When working with Python 3, use pip3. If you want to make sure “pip3” is ran even if you type “pip”, add an alias to your bashrc: echo "alias pip=pip3" >> ~/.bashrc.

Now, to see the list of all Python 3 modules, run pip3 list. For each module you’ll also get the installed version.

If you want to filter the results, add “grep”:

$ pip3 list | grep "camera"picamera 1.13

To install a new module, run pip3 install module_name. And to remove it, pip3 uninstall module_name.

Once you’ve installed a module with pip3 in the terminal, you can easily check if the module can be found: open a Python shell and try to import the module. In 10 seconds you’ll know if things are working.

Conclusion – running a Python script from the terminal in your Raspberry Pi

In this tutorial you’ve seen how to configure your Raspberry Pi so that you can run a Python script from the terminal.

When you start with Raspberry Pi and Python 3, it’s good to use the Thonny Python IDE at first, which will allow you to focus on learning Python. Then, using the terminal is a mandatory step if you want to get a better understanding and go further.

And in the end, once you know how to use Python inside the terminal, it becomes a matter of preference. Some developers prefer using only the terminal, others prefer using IDEs to develop. This is your choice to make!

Raspberry Pi - Run Python Script in the Terminal - The Robotics Back-End (2024)

FAQs

How do I run a Python program on Raspberry Pi? ›

To open this, click the Raspbian logo and then navigate to Programming > Python 3 (IDLE). With the IDE loaded, click File > Open and then navigate to your Python program. When the file opens, you can run the program by clicking Run > Run Module or by pressing F5 on the keyboard.

How do I write a Python script on Raspberry Pi? ›

Open IDLE by selecting the Raspberry Pi logo in the top-left, and click Programming > Python 3 (IDLE). You should be presented with the Python interactive interpreter. To write a program, go to File > New File. Enter in your code.

How do I run a Python script in terminal? ›

To run Python scripts with the python command, you need to open a command-line and type in the word python , or python3 if you have both versions, followed by the path to your script, just like this: $ python3 hello.py Hello World!

How do I run a program from Raspberry Pi terminal? ›

Re: How to execute installed program
  1. Open up a command line terminal. You will see a command line prompt like: ...
  2. Type the command for the Free Pascal compiler: Code: Select all pi@raspberrypi:~$ fpc. ...
  3. Now that you know it is installed and runs correctly will want to compile your program:
Feb 2, 2018

What is Raspberry Pi terminal? ›

The terminal is a really useful application: it allows you to navigate file directories and control your Raspberry Pi using typed commands instead of clicking on menu options. It's often in many tutorials and project guides, including the ones on our website.

How do I autorun a Python script? ›

Method 2: Using Windows Task Scheduler.

Step 1: Open Task Scheduler Application on your Windows Machine. Step 2: Click on 'Create Basic Task…. ' in the Actions Tab. And give a suitable Name and Description of your task that you want to Automate and click on Next.

How do I save a Python script in terminal? ›

Saving your work

Right-click the Python window and select Save As to save your code either as a Python file (. py) or Text file (. txt). If saving to a Python file, only the Python code will be saved.

How do I start Python script from boot? ›

Show activity on this post.
  1. click Win+R.
  2. type shell:startup.
  3. drag and drop your python file my_script.py. if you don't need the console: change extension from my_script.py to my_script.pyw. else: create run_my_script.cmd with content: python path\to\your\my_script.py.

How do I run a file in terminal? ›

About This Article
  1. Open the Terminal.
  2. Type "cd" followed by the path of the file and press Enter.
  3. Type "sudo chmod +x " to change allow yourself permission to edit the file.
  4. Type "./" to run the file.
May 10, 2021

How do I run a Python function from terminal arguments? ›

You can use the command line arguments by using the sys. argv[] array. The first index of the array consists of the python script file name. And from the second position, you'll have the command line arguments passed while running the python script.

How do you call Python shell from command line? ›

To run the Python Shell, open the command prompt or power shell on Windows and terminal window on mac, write python and press enter. A Python Prompt comprising of three greater-than symbols >>> appears, as shown below. Now, you can enter a single statement and get the result.

How do I create a Raspberry Pi script? ›

Basics: Writing Your First Script with Raspberry Pi
  1. /home/pi/bin.
  2. Navigate into ~/bin and use nano to create a file called first_script.
  3. Finally, the last line is an echo command. ...
  4. From in the ~/bin directory, list the files using ls -l and you should see your brand new script!
  5. chmod g+rx first_script.
Jun 14, 2017

Is Raspberry Pi good for learning Python? ›

Raspberry Pi chose Python as its teaching language of choice to encourage a new generation of programmers to learn how to program. This approachable book serves as an ideal resource for anyone wanting to use Raspberry Pi to learn to program and helps you get started with the Python programming language.

Is Raspberry Pi good for programming? ›

Raspberry Pi is an excellent device for programmers, and it is especially great when learning how to code. It has been created with this goal in mind and lets you experiment with Python, Java, and other languages. The default operating system includes all the applications to get started quickly.

Which command comes under Raspberry Pi terminal commands? ›

System Information Commands

cat /proc/meminfo: Shows details about your memory. cat /proc/partitions: Shows the size and number of partitions on your SD card or hard drive. cat /proc/version: Shows you which version of the Raspberry Pi you are using. df -h: Shows information about the available disk space.

How do I open a Raspberry Pi terminal in Windows? ›

SSH from Windows
  1. Download & install the PuTTy application.
  2. Enter the Pi's ip address in the Host Name Box on port 22.
  3. Select SSH as connection type.
  4. Click Open button.
  5. Accept the Server's key finger print.
  6. Login as user pi with the password raspberry by default.
Jun 22, 2021

How do I create a new file in Raspberry Pi terminal? ›

To create a new file using the Raspberry Pi terminal, we do the following:
  1. Open the terminal.
  2. Navigate to the directory where you want to store the file cd /directory .
  3. If you are using GNU Nano text editor, use the command sudo nano my_file. txt .
  4. Here, we are creating a new text file called "my_file" and has a (.

How do you type on a Raspberry Pi? ›

Using the Desktop to Open the On-Screen Keyboard

Once you are on the desktop of your Raspberry Pi, click the icon in the top-left hand corner of the screen. This icon will bring up the start menu for the operating system. Within this new menu, click “Keyboard” (2.) to launch the software.

How do I make a script run automatically? ›

On Windows, the simplest way of running a program at startup is to place an executable file in the Startup folder. All the programs that are in this folder will be executed automatically when the computer opens. You can open this folder more easily by pressing WINDOWS KEY + R and then copying this text shell:startup .

How do I Auto Start a program on Raspberry Pi? ›

How to auto start a program
  1. 1 – Use the crontab. Cron is a service, automatically started at each boot of the Raspberry Pi, which allows the user to execute scheduled commands. ...
  2. 2 – Put your script in /etc/init. d. ...
  3. 3 – Create an upstart job. The third option is to create an upstart job. ...
  4. 4 – Add a line in /etc/rc. local.

How do you save code in terminal? ›

Here's how to do so via Terminal.
  1. In Terminal, type the command you need to save.
  2. Drag your cursor to highlight the command.
  3. Right-click on it and click Copy.
  4. The command you entered has now been saved to your clipboard and can be pasted elsewhere.
Aug 22, 2021

How do I write a Python script in Linux terminal? ›

Linux (advanced)Edit
  1. save your hello.py program in the ~/pythonpractice folder.
  2. Open up the terminal program. ...
  3. Type cd ~/pythonpractice to change directory to your pythonpractice folder, and hit Enter.
  4. Type chmod a+x hello.py to tell Linux that it is an executable program.
  5. Type ./hello.py to run your program!

How do I run a Raspberry Pi script? ›

How to Run a Script at Raspberry Pi Boot
  1. Edit your crontab list by typing: sudo crontab -e. ...
  2. Select nano if you are prompted to ask for an editor. Advertisem*nt. ...
  3. Add a line at the end of the file that reads like this: @reboot python3 /home/pi/myscript.py. ...
  4. Save and exit. ...
  5. Make your script executable if it is a Bash script.
Jul 4, 2020

How do I open command prompt on Raspberry Pi? ›

Firstly, open a terminal window and enter “sudo raspi-config”. This should bring up a menu option, as seen below. Once the menu loads, select item 3, which should be called “Boot Options”. Select the first option in the list called “Desktop / CLI”.

Does Raspberry Pi use Python 2 or 3? ›

Use Python 3

By default, Raspbian (Stretch version April 2018 and earlier) uses Python 2. However, versions 2 and 3 come installed by default. We just have to make 1 minor change so that the Pi uses Python 3 whenever we type python into a terminal. You should see which version is being used by default.

Top Articles
Latest Posts
Article information

Author: Allyn Kozey

Last Updated:

Views: 5552

Rating: 4.2 / 5 (43 voted)

Reviews: 90% of readers found this page helpful

Author information

Name: Allyn Kozey

Birthday: 1993-12-21

Address: Suite 454 40343 Larson Union, Port Melia, TX 16164

Phone: +2456904400762

Job: Investor Administrator

Hobby: Sketching, Puzzles, Pet, Mountaineering, Skydiving, Dowsing, Sports

Introduction: My name is Allyn Kozey, I am a outstanding, colorful, adventurous, encouraging, zealous, tender, helpful person who loves writing and wants to share my knowledge and understanding with you.