How To Run Python Code In Linux : Debugging Syntax Errors Locally

Running Python code in Linux is as simple as invoking the interpreter directly from the terminal. If you’re new to Linux or Python, you might be wondering how to run python code in linux without getting lost in commands or configurations. This guide walks you through every practical method, from the terminal basics to running scripts automatically.

Python comes pre-installed on most Linux distributions. You can check your version by typing python3 --version in the terminal. If it’s missing, install it with your package manager.

The core idea is simple: write your code in a file, then tell Python to execute it. But there are multiple ways to do this, each suited for different tasks.

How To Run Python Code In Linux

Running Python Scripts Directly From The Terminal

The most common method is running a script file. Open your terminal and navigate to the directory containing your Python file.

  1. Create a file called hello.py with this content:
print("Hello, Linux!")
  1. Run it with:
python3 hello.py

You’ll see the output printed right in the terminal. This works for any Python script, no matter how complex.

If you have multiple Python versions installed, use python3.11 or python3.12 instead of just python3.

Using The Interactive Python Shell

Sometimes you just want to test a line or two. The interactive shell is perfect for that.

Type python3 in your terminal. You’ll see a prompt like >>>. Now you can type Python code directly:

>>> print("Testing")
Testing
>>> 2 + 2
4

Exit the shell with exit() or press Ctrl+D. This is great for quick experiments or debugging small snippets.

One common mistake is forgetting to call exit() properly. Just type it with parentheses.

Making Python Scripts Executable

You can run Python scripts like any other program, without typing python3 every time. This is called making the script executable.

First, add a shebang line at the very top of your script:

#!/usr/bin/env python3
print("This runs like a command")

Then give the file execute permissions:

chmod +x hello.py

Now you can run it with just ./hello.py. The shebang tells the system to use Python to interpret the file.

Make sure the shebang points to the correct Python path. Use which python3 to find it if you’re unsure.

Running Python Code Without A File

You can execute Python code directly from the command line using the -c flag. This is handy for one-liners.

python3 -c "print('Inline code')"

You can also pipe code from another command:

echo "print('Piped')" | python3

This method is useful in scripts or when you want to test something quickly without creating a file.

Be careful with quotes and escaping. Use double quotes for the outer string if your code contains single quotes.

Running Python Scripts With Arguments

Many scripts accept command-line arguments. You can pass them just like any other program.

Create a script called greet.py:

import sys
name = sys.argv[1]
print(f"Hello, {name}!")

Run it with:

python3 greet.py Alice

Output: Hello, Alice!

You can pass multiple arguments separated by spaces. Access them with sys.argv[2], sys.argv[3], and so on.

Always check that the user provided the expected number of arguments. Otherwise your script might crash with an IndexError.

Using Virtual Environments

Virtual environments let you isolate Python dependencies for different projects. This is essential when you have multiple projects with conflicting requirements.

Create a virtual environment:

python3 -m venv myenv

Activate it:

source myenv/bin/activate

Now any Python code you run will use the environment’s packages. Install packages with pip without affecting your system Python.

To deactivate, simply type deactivate.

Always activate the environment before running your script. Forgetting this is a common source of “module not found” errors.

Running Python Scripts In The Background

Long-running Python scripts can be sent to the background so you can continue using the terminal.

Add an ampersand at the end of the command:

python3 long_script.py &

The script runs in the background. You’ll see a job number and process ID. Bring it back to the foreground with fg.

For scripts that should keep running after you log out, use nohup:

nohup python3 long_script.py &

Output is saved to nohup.out by default. You can redirect it to a specific file:

nohup python3 script.py > output.log &

Running Python Code With Cron

Automate your Python scripts to run at scheduled times using cron. This is perfect for backups, reports, or monitoring tasks.

Edit your crontab file:

crontab -e

Add a line like this to run a script every day at 8 AM:

0 8 * * * /usr/bin/python3 /home/user/script.py

Use absolute paths for both the Python interpreter and the script. Cron has a limited environment, so relative paths might not work.

Redirect output to a log file to debug issues:

0 8 * * * /usr/bin/python3 /home/user/script.py >> /home/user/log.txt 2>&1

Running Python Code In Docker

Docker containers provide a consistent environment for running Python code. This eliminates “it works on my machine” problems.

Create a Dockerfile:

FROM python:3.11-slim
COPY script.py /app/script.py
CMD ["python3", "/app/script.py"]

Build the image:

docker build -t my-python-app .

Run it:

docker run my-python-app

You can pass arguments too:

docker run my-python-app python3 /app/script.py arg1 arg2

Debugging Python Code In Linux

When your code doesn’t work as expected, use these debugging techniques.

Run the script with the -i flag to enter interactive mode after execution:

python3 -i script.py

This lets you inspect variables and test functions after the script finishes.

Use Python’s built-in debugger pdb. Insert this line where you want to pause:

import pdb; pdb.set_trace()

Then step through your code line by line.

For simple debugging, add print() statements to see what’s happening. This is often the fastest approach.

Running Python Code With IDEs And Text Editors

Many Linux users prefer IDEs like VS Code, PyCharm, or Vim with plugins. These tools let you run code with a single click or keyboard shortcut.

In VS Code, open your Python file and press Ctrl+F5 to run without debugging. Or click the play button in the top right corner.

In Vim, you can run the current file with :!python3 %. This executes the file and shows output in a split window.

IDEs also provide integrated terminals, debuggers, and linting tools that make development smoother.

Common Errors And How To Fix Them

Here are frequent issues when running Python code in Linux and their solutions.

Command not found: python3
Install Python with sudo apt install python3 (Debian/Ubuntu) or sudo dnf install python3 (Fedora).

Permission denied
Make the script executable with chmod +x script.py.

ModuleNotFoundError
Install the missing module with pip3 install module_name. If using a virtual environment, activate it first.

SyntaxError
Check your Python version. Code written for Python 3 might not run on Python 2. Use python3 explicitly.

IndentationError
Python relies on consistent indentation. Use spaces (preferably 4) and don’t mix tabs and spaces.

Frequently Asked Questions

How Do I Run A Python Script In Linux Terminal?

Navigate to the script’s directory and type python3 script_name.py. Make sure Python is installed first.

Can I Run Python Code Without Saving It To A File?

Yes, use python3 -c "your code here" for one-liners, or type python3 to enter the interactive shell.

What Is The Shebang Line And Why Do I Need It?

The shebang (#!/usr/bin/env python3) tells the system which interpreter to use. It allows you to run scripts like ./script.py without typing python3.

How Do I Run A Python Script Automatically On Startup?

Add the command to your crontab with @reboot /path/to/python3 /path/to/script.py. Or add it to your system’s init system (systemd, init.d).

Why Does My Python Script Run Differently In Cron Than In The Terminal?

Cron uses a limited environment. Always use absolute paths for files and Python interpreter. Redirect output to a log file for debugging.

Conclusion

Running Python code in Linux is straightforward once you know the different methods. Start with the terminal and script files, then explore virtual environments, background execution, and automation with cron. Each method has its place, and mastering them all makes you a more productive Python developer on Linux.

Remember to always use python3 instead of python to avoid accidentally using Python 2. Keep your scripts organized in separate directories, and use virtual environments for every project. With these skills, you can run any Python code on Linux with confidence.