Executing a Python script in Linux is straightforward once you verify the script’s syntax. If you’re new to Linux or just need a refresher on how to run a python script in linux, this guide will walk you through every step. We’ll cover the basics, advanced methods, and common pitfalls so you can get your code running fast.
Python is one of the most popular languages for Linux users, from beginners to system administrators. Knowing how to execute your scripts efficiently saves time and reduces frustration. Let’s start with the simplest approach and build up from there.
Prerequisites For Running Python Scripts
Before you run any Python script, make sure Python is installed on your system. Most Linux distributions come with Python pre-installed, but it’s worth checking.
Open your terminal and type:
python3 --version
If you see a version number, you’re good. If not, install Python using your package manager. For Debian/Ubuntu, use sudo apt install python3. For Fedora, use sudo dnf install python3.
You’ll also need a text editor to write your script. Nano, Vim, or VS Code all work fine. For this guide, we’ll assume you have a simple script named hello.py ready to go.
How To Run A Python Script In Linux
The most common method is using the Python interpreter directly. Open your terminal, navigate to the directory containing your script, and type:
python3 script_name.py
Replace script_name.py with your actual file name. For example, if your script is hello.py, you’d run:
python3 hello.py
This tells the system to use Python 3 to execute the file. If you have multiple Python versions installed, you might need to specify python3.10 or similar.
That’s the core answer to how to run a python script in linux. But there are several other methods worth knowing, especially for automation and convenience.
Making The Script Executable Directly
You can run a Python script like any other program by making it executable. First, add a shebang line at the top of your script:
#!/usr/bin/env python3
This tells the system which interpreter to use. Then, change the file permissions to make it executable:
chmod +x hello.py
Now you can run it directly:
./hello.py
No need to type python3 every time. This is handy for scripts you use often.
Running Python Scripts With Arguments
Many scripts accept command-line arguments. To pass arguments, simply add them after the script name:
python3 script.py arg1 arg2
Inside your script, you can access these using sys.argv. For example:
import sys
print(sys.argv[1]) # prints arg1
This is useful for scripts that process files or take user input.
Using Python’s Interactive Mode
Sometimes you just want to test a few lines of code without creating a file. Type python3 in the terminal to enter interactive mode. You’ll see a >>> prompt where you can type Python commands directly.
To run a script from within interactive mode, use:
exec(open('script.py').read())
Or use the run command if you’re using IPython.
Running Scripts In The Background
For long-running scripts, you might want them to keep running even after you close the terminal. Use the & symbol to run in the background:
python3 script.py &
You can also use nohup to ignore hangup signals:
nohup python3 script.py &
This writes output to nohup.out by default. Check that file to see your script’s output.
Using Virtual Environments
Virtual environments keep your project dependencies isolated. First, create one:
python3 -m venv myenv
Activate it:
source myenv/bin/activate
Now when you run python script.py, it uses the environment’s Python and packages. Deactivate with deactivate.
This is essential for managing different projects with conflicting dependencies.
Common Errors And Fixes
Even experienced users run into issues. Here are the most common problems when trying to run Python scripts on Linux.
Permission Denied
If you see “Permission denied,” your script isn’t executable. Use chmod +x script.py to fix it. Alternatively, run it with python3 script.py instead of ./script.py.
Command Not Found
This usually means Python isn’t installed or the terminal can’t find it. Check with which python3. If nothing shows, install Python as described earlier.
Syntax Errors
If you get syntax errors, double-check your code. Common mistakes include missing colons, indentation issues, or using Python 2 syntax with Python 3. Run python3 -m py_compile script.py to check syntax without executing.
Module Not Found
Missing modules are common. Install them with pip3 install module_name. Make sure you’re using the same Python environment where you installed the module.
Advanced Execution Methods
Once you’re comfortable with the basics, these advanced techniques can streamline your workflow.
Using Cron For Scheduled Execution
Cron lets you run scripts automatically at set times. Edit your crontab with crontab -e and add a line like:
0 9 * * * /usr/bin/python3 /home/user/script.py
This runs the script every day at 9 AM. Adjust the time and path as needed.
Running Scripts With Systemd
For more control, create a systemd service. Create a file at /etc/systemd/system/myscript.service with:
[Unit]
Description=My Python Script
[Service]
ExecStart=/usr/bin/python3 /path/to/script.py
Restart=always
[Install]
WantedBy=multi-user.target
Then enable and start it:
sudo systemctl enable myscript.service
sudo systemctl start myscript.service
This keeps your script running even after reboots.
Using Shebang With Environment Variables
The shebang line #!/usr/bin/env python3 is flexible because it uses the env command to find Python in the user’s PATH. This works well with virtual environments.
You can also specify a full path like #!/usr/bin/python3 for more control, but it’s less portable.
Best Practices For Running Python Scripts
Follow these tips to avoid headaches and keep your scripts reliable.
- Always use
python3instead ofpythonto avoid accidentally using Python 2. - Keep scripts in a dedicated directory like
~/scriptsand add it to your PATH. - Use version control like Git to track changes.
- Add error handling to your scripts so they fail gracefully.
- Test scripts with small inputs before running on real data.
Also, consider using a shebang line even if you usually run scripts with python3. It makes your scripts more portable and self-documenting.
Debugging Scripts That Won’t Run
When a script fails, start with these checks:
- Verify the file exists:
ls -l script.py - Check Python version:
python3 --version - Look for syntax errors:
python3 -m py_compile script.py - Run with verbose output:
python3 -v script.py - Check file permissions:
ls -l script.py(should show-rwxr-xr-xfor executable)
If you’re still stuck, add print statements to trace execution. Or use Python’s debugger: python3 -m pdb script.py.
Running Python Scripts From Other Programs
You can call Python scripts from shell scripts, other Python scripts, or even web applications.
From a shell script, just call it like any command:
#!/bin/bash
python3 /path/to/script.py
From another Python script, use subprocess:
import subprocess
subprocess.run(['python3', 'script.py'])
This gives you more control over input and output.
Frequently Asked Questions
What Is The Difference Between Python And Python3 Commands?
On many Linux systems, python refers to Python 2, while python3 refers to Python 3. Always use python3 to ensure you’re using the modern version. Some distributions now alias python to Python 3, but it’s safer to be explicit.
Can I Run A Python Script Without The .Py Extension?
Yes, you can. The extension doesn’t affect execution. Just make sure the file has a shebang line and is executable. For example, you can name it myscript and run it with ./myscript.
How Do I Run A Python Script As Root?
Use sudo python3 script.py or sudo ./script.py if it’s executable. Be careful running scripts as root—only do this if you trust the script and understand what it does.
Why Does My Script Run In One Directory But Not Another?
This usually happens because of relative file paths. If your script opens files using relative paths, it expects to be run from the directory containing those files. Use absolute paths or change to the correct directory first with cd.
How Can I Run A Python Script Automatically At Startup?
You can add the script to your crontab with @reboot, or create a systemd service as shown earlier. Another option is to add the command to ~/.bashrc or ~/.profile, but that runs it every time you open a terminal.
Conclusion
Now you know multiple ways to run Python scripts on Linux. Start with the simple python3 script.py method, then explore making scripts executable, using arguments, and automating with cron or systemd. The key is to practice and understand the environment your script runs in.
Remember to always check your Python version and permissions first. With these skills, you’ll be able to run any Python script confidently, whether it’s a quick test or a production automation tool. Keep experimenting and happy coding.