How To Run A Python File In Linux : Python File Run Linux Terminal Commands

Python files in Linux run best when you ensure the correct Python version is installed. Knowing how to run a python file in linux is a fundamental skill for any developer or system administrator. Whether you are automating tasks, building web applications, or analyzing data, executing Python scripts efficiently on a Linux system can save you time and frustration.

This guide walks you through every method to run a Python file in Linux, from the simplest command-line approach to advanced techniques like using virtual environments and cron jobs. You will learn how to handle permissions, dependencies, and common errors. By the end, you will be able to run any Python script with confidence.

How To Run A Python File In Linux

Let’s start with the most common and straightforward way to execute a Python script. Open your terminal and type python3 filename.py. Replace filename.py with the actual name of your Python file. This command tells the system to use the Python 3 interpreter to run the script.

If you have multiple Python versions installed, you might need to specify python3.10 or python3.11 instead. Check your installed versions with python3 --version.

Step-By-Step: Running A Python File Directly

  1. Open your terminal emulator (Ctrl+Alt+T on most distributions).
  2. Navigate to the directory containing your Python file using cd /path/to/your/file.
  3. Run the script with python3 your_script.py.
  4. Press Enter and watch the output appear in the terminal.

That is the basic method. But there is more to learn for efficient and professional usage.

Making A Python File Executable

You can run a Python file like any other program by making it executable. This eliminates the need to type python3 every time. Add a shebang line at the top of your script and set the execute permission.

Adding The Shebang Line

The shebang line tells the system which interpreter to use. Open your Python file with a text editor and add this as the very first line:

#!/usr/bin/env python3

This line searches for the Python 3 interpreter in the user’s PATH. It is more portable than hardcoding a specific path like /usr/bin/python3.

Setting Execute Permissions

After adding the shebang, you need to make the file executable. Use the chmod command:

chmod +x your_script.py

Now you can run the script directly from the terminal:

./your_script.py

This method is cleaner and more convenient for scripts you use frequently.

Using Python Virtual Environments

Virtual environments isolate your project dependencies. They prevent conflicts between different projects that require different package versions. Running a Python file inside a virtual environment ensures you use the correct libraries.

Creating And Activating A Virtual Environment

  1. Navigate to your project directory.
  2. Create a virtual environment: python3 -m venv myenv.
  3. Activate it: source myenv/bin/activate.
  4. Your terminal prompt will change, indicating the environment is active.
  5. Install required packages with pip install package_name.
  6. Run your Python file as usual: python3 your_script.py.

To deactivate the environment, simply type deactivate. This keeps your global Python installation clean.

Running Python Files With Arguments

Many scripts accept command-line arguments. You pass them after the filename. For example:

python3 your_script.py arg1 arg2 --option value

Inside your script, you can access these arguments using sys.argv or libraries like argparse. This makes your scripts flexible and reusable.

Example: Passing Arguments

Create a simple script called greet.py:

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

Run it with:

python3 greet.py Alice

Output: Hello, Alice!

Running Python Files In The Background

Sometimes you need a script to run even after you close the terminal. Use the & symbol to run it in the background:

python3 your_script.py &

This returns the process ID (PID). You can bring it back to the foreground with fg or kill it with kill PID. For long-running scripts, consider using nohup:

nohup python3 your_script.py &

This prevents the script from being terminated when you log out. Output is saved to nohup.out by default.

Using Cron To Schedule Python Scripts

Cron is a time-based job scheduler in Linux. You can automate your Python scripts to run at specific intervals. This is perfect for backups, data fetching, or system monitoring.

Setting Up A Cron Job

  1. Open your crontab file: crontab -e.
  2. Add a line specifying the schedule and command. For example, to run a script every day at 2 AM:
0 2 * * * /usr/bin/python3 /path/to/your_script.py

Make sure to use the full path to the Python interpreter and your script. Save and exit. Cron will now execute your script automatically.

Running Python Files With Different Interpreters

You might have Python 2, Python 3, or even PyPy installed. To run a file with a specific interpreter, use the full path:

/usr/bin/python2.7 your_script.py

Or for PyPy:

pypy3 your_script.py

Check available interpreters with which python3 or ls /usr/bin/python*.

Debugging Common Errors

When learning how to run a python file in linux, you will encounter errors. Here are the most common ones and how to fix them.

Permission Denied

If you see Permission denied, the file lacks execute permission. Run chmod +x your_script.py to fix it.

Command Not Found: Python3

This means Python 3 is not installed. Install it with your package manager:

sudo apt install python3   # Debian/Ubuntu
sudo yum install python3   # CentOS/RHEL

ModuleNotFoundError

Your script imports a module that is not installed. Use pip install module_name to install it. If using a virtual environment, activate it first.

SyntaxError

This usually happens when you run a Python 2 script with Python 3, or vice versa. Check the shebang line and use the correct interpreter.

Running Python Files From Any Directory

If you want to run a script from anywhere without specifying the full path, add the script’s directory to your PATH. Edit your ~/.bashrc or ~/.bash_profile file:

export PATH="$PATH:/path/to/your/scripts"

Then reload with source ~/.bashrc. Now you can run your_script.py from any location.

Using IDEs And Text Editors

You don’t have to use the terminal exclusively. Many integrated development environments (IDEs) allow you to run Python files with a single click.

Running In VS Code

  1. Open your Python file in VS Code.
  2. Press Ctrl+F5 to run without debugging.
  3. Or click the play button in the top-right corner.

Running In PyCharm

  1. Open your project in PyCharm.
  2. Right-click the file and select Run 'filename'.
  3. Or use the Shift+F10 shortcut.

These tools handle the terminal commands for you, but understanding the underlying process is still valuable.

Running Python Files With Shebang And PATH

For scripts you use daily, you can place them in a directory included in your PATH, like ~/bin or /usr/local/bin. Then you can run them like any system command.

  1. Create a ~/bin directory: mkdir -p ~/bin.
  2. Move or copy your script there: cp your_script.py ~/bin/.
  3. Make sure the script has a shebang and execute permission.
  4. Add ~/bin to your PATH in ~/.bashrc: export PATH="$HOME/bin:$PATH".
  5. Reload: source ~/.bashrc.
  6. Now run your_script.py from anywhere.

Running Python Files With Input Redirection

You can feed input to a Python script from a file or another command. Use the < operator:

python3 your_script.py < input.txt

This reads the contents of input.txt as standard input. Similarly, you can redirect output:

python3 your_script.py > output.txt

Combine both for full control:

python3 your_script.py < input.txt > output.txt

Running Python Files With Docker

If you work with containers, you can run Python files inside a Docker container. This ensures a consistent environment across different systems.

  1. Create a Dockerfile with the Python base image.
  2. Copy your script into the container.
  3. Build the image: docker build -t my-python-app .
  4. Run the container: docker run my-python-app.

This method is excellent for deployment and testing in isolated environments.

Performance Considerations

When running large Python files, consider using python3 -O for optimized bytecode. This removes assert statements and debug info, speeding up execution slightly.

For CPU-intensive tasks, you might use PyPy, a Just-In-Time compiler that can run Python code much faster. Install it with sudo apt install pypy3 and run your script with pypy3 your_script.py.

Security Best Practices

Never run a Python script from an untrusted source without reviewing it first. Malicious code can damage your system or steal data. Always check the script’s contents, especially if it requires root privileges.

Use virtual environments to avoid global package conflicts. Avoid running scripts with sudo unless absolutely necessary. If you must, understand what the script does.

Frequently Asked Questions

How do I run a Python file in Linux if I get "command not found"?

Install Python 3 using your package manager. For Ubuntu, run sudo apt install python3. For CentOS, use sudo yum install python3. Then try again.

Can I run a Python file without the .py extension?

Yes. The extension is not required. You can name the file anything and run it with python3 filename. However, using .py helps with syntax highlighting and file recognition.

What is the difference between python and python3?

On many Linux systems, python points to Python 2, while python3 points to Python 3. Always use python3 for new projects to avoid compatibility issues.

How do I run a Python file in the background and keep it running after logout?

Use nohup python3 your_script.py &. This prevents the script from being killed when you close the terminal. Output goes to nohup.out.

Why does my Python script run fine in the terminal but not from cron?

Cron uses a limited PATH. Always use full paths to the Python interpreter and your script. Also, ensure the script has execute permission and the shebang line is correct.

Final Tips For Running Python Files In Linux

Practice these methods regularly to build muscle memory. Start with simple scripts and gradually move to more complex ones. Use version control like Git to track changes.

Always check the Python version before running a script. Mismatched versions cause frustrating errors. Keep your system and packages updated.

If you are new to Linux, take time to learn basic terminal commands like cd, ls, chmod, and nano. They will make running Python files much easier.

Remember that the terminal is your friend. It gives you full control over how your scripts execute. Embrace it, and you will become a more effective developer.

Now you have a complete understanding of how to run a python file in linux. From simple execution to advanced scheduling and containerization, you can handle any scenario. Go ahead and run your first script with confidence.