Executing a Python file in Linux requires either calling python3 filename.py or setting the file as executable. If you are new to Linux or just starting with Python, understanding how to run python file in linux is a fundamental skill you need to master. This guide walks you through every method, from the simplest command to advanced scripting techniques, ensuring you can run your code without frustration.
Linux offers multiple ways to execute Python scripts. Whether you prefer typing commands in the terminal or making files clickable, there is a solution for you. Let’s start with the basics and build up to more efficient workflows.
Prerequisites For Running Python On Linux
Before you run any Python file, you need to ensure Python is installed on your system. Most Linux distributions come with Python pre-installed, but you should verify this.
Open your terminal and type:
python3 --version
If you see a version number like Python 3.10.12, you are good to go. If not, install Python using your package manager:
- For Debian/Ubuntu:
sudo apt install python3 - For Fedora:
sudo dnf install python3 - For Arch:
sudo pacman -S python
You also need a text editor to write your Python code. Nano, Vim, or VS Code all work fine. Create a simple test file named hello.py with the following content:
print("Hello, Linux!")
Now you are ready to learn the main methods.
How To Run Python File In Linux
This section covers the primary technique for executing Python scripts. The most common approach is using the terminal with the Python interpreter. Here is the step-by-step process.
Method 1: Using The Python3 Command Directly
This is the simplest way to run a Python file. Navigate to the directory containing your script using the cd command.
- Open your terminal.
- Type
cd /path/to/your/fileand press Enter. - Run the script with:
python3 hello.py
The output will appear directly in the terminal. This method works for any Python file, regardless of permissions. It is ideal for quick tests and one-off executions.
If you have multiple Python versions installed, you might use python3.11 or python3.10 instead. Check which version you need for your project.
Method 2: Making The File Executable
For scripts you run frequently, making them executable saves time. You add a shebang line at the top of your file and change its permissions.
First, edit your hello.py file to include this first line:
#!/usr/bin/env python3
This tells the system to use the Python interpreter. Next, make the file executable with:
chmod +x hello.py
Now you can run it simply by typing:
./hello.py
No need to type python3 every time. This method is prefered for scripts you run often or share with others.
Method 3: Running Python With The -M Flag
Sometimes you want to run a module rather than a file. The -m flag lets you execute modules like pip or venv. For standard files, this is less common but still usefull.
Example: python3 -m hello (without the .py extension). This works if the file is in your Python path.
Common Issues And Fixes
Even simple commands can fail. Here are typical problems you might encounter and how to solve them.
File Not Found Error
If you see No such file or directory, check your current directory. Use pwd to print the working directory and ls to list files. Make sure the filename is spelled correctly, including case.
Permission Denied
When trying to run an executable script, you might get a permission error. Use chmod +x filename.py to add execute permissions. Alternatively, run with python3 filename.py which does not require execute permission.
Module Import Errors
If your script imports external libraries, you need to install them first. Use pip install package_name. For Python 3, you might need pip3 instead.
Shebang Line Issues
If you use #!/usr/bin/env python3 and it fails, check that python3 is in your PATH. You can find it with which python3. Alternatively, use the direct path like #!/usr/bin/python3.
Advanced Execution Techniques
Once you master the basics, these advanced methods will streamline your workflow even more.
Running Python In The Background
For long-running scripts, you can run them in the background using & at the end:
python3 long_script.py &
This returns the terminal prompt immediately. Use jobs to see background processes and fg to bring one to the foreground.
Using Virtual Environments
Virtual environments keep dependencies isolated. Create one with:
python3 -m venv myenv
Activate it with:
source myenv/bin/activate
Now run your script normally. The environment ensures you use the correct Python version and packages.
Passing Command Line Arguments
Your script can accept arguments. For example, if you have script.py that uses sys.argv, run it like:
python3 script.py arg1 arg2
Access these inside your script with sys.argv[1] and sys.argv[2].
Running Python With Cron
Automate script execution using cron jobs. Edit your crontab with crontab -e and add a line like:
0 8 * * * /usr/bin/python3 /home/user/script.py
This runs the script daily at 8 AM. Make sure to use absolute paths.
Choosing The Right Method For Your Needs
Each method has its best use case. Here is a quick comparison to help you decide.
- python3 filename.py: Best for quick tests and one-time runs. No permission changes needed.
- Executable script: Ideal for scripts you run daily or share. Requires shebang and chmod.
- Background execution: Perfect for long processes like data scraping or servers.
- Virtual environments: Essential for projects with specific dependencies.
- Cron jobs: For scheduled, unattended execution.
Most developers start with the direct command and move to executable scripts as their projects grow.
Debugging Python Scripts In Linux
When your script does not work as expected, debugging tools help. The simplest method is adding print statements to see variable values.
For more advanced debugging, use Python’s built-in debugger:
python3 -m pdb script.py
This starts an interactive debugger where you can step through code, set breakpoints, and inspect variables. Common commands include n for next line, c for continue, and q to quit.
You can also use pdb.set_trace() inside your script to pause execution at a specific point.
Best Practices For Running Python On Linux
Follow these guidelines to avoid common pitfalls and keep your workflow efficient.
- Always use
python3instead ofpythonto avoid confusion with Python 2. - Keep your scripts organized in dedicated directories.
- Use meaningful filenames with .py extension.
- Add shebang lines to all executable scripts.
- Test your script with a small input before running on large data.
- Use version control like Git to track changes.
These habits will save you time and prevent errors down the road.
Frequently Asked Questions
How Do I Run A Python File In Linux Terminal?
Open the terminal, navigate to the file’s directory with cd, then type python3 filename.py and press Enter. This works for any Python script.
Can I Run A Python File Without Typing Python3 Every Time?
Yes. Add #!/usr/bin/env python3 as the first line of your script, then run chmod +x filename.py. Now you can execute it with ./filename.py.
What If I Get A “Command Not Found” Error For Python3?
Python 3 is not installed. Install it using your package manager: sudo apt install python3 for Debian-based systems, or sudo dnf install python3 for Fedora.
How Do I Run A Python Script In The Background?
Add an ampersand at the end: python3 script.py &. To keep it running after closing the terminal, use nohup python3 script.py &.
What Is The Difference Between Python And Python3 On Linux?
On many systems, python refers to Python 2 (if installed), while python3 refers to Python 3. Always use python3 to ensure you are using the modern version.
Conclusion
Now you know multiple ways to run Python files on Linux. Start with the simple python3 filename.py command, then experiment with executable scripts and background processes. The key is practice—run a few test files today to build confidence.
Remember to check your Python version, use the correct permissions, and leverage virtual environments for larger projects. With these skills, you can automate tasks, build applications, and explore the full power of Python on Linux.