Running a Python script in Linux means the interpreter reads your code line by line from the terminal. This guide shows you exactly how to run python script in linux with clear steps, no matter your skill level.
Python is one of the most popular languages for Linux users. It’s used for automation, data analysis, web development, and system administration. The good news is that Linux makes running Python scripts incredibly straightforward.
Let’s get you started right away.
Prerequisites For Running Python On Linux
Before you run any script, you need to confirm Python is installed. Most Linux distributions come with Python pre-installed. But you should check the version.
Open your terminal. Type this command:
python3 --version
If you see something like Python 3.10.12, you’re good to go. If not, install Python using your package manager.
For Ubuntu or Debian:
sudo apt updatesudo apt install python3
For Fedora or CentOS:
sudo dnf install python3
For Arch Linux:
sudo pacman -S python
Thats all you need. Now let’s run some scripts.
How To Run Python Script In Linux
This is the core section you came for. There are several ways to execute a Python script in Linux. I’ll show you each method with examples.
Method 1: Using The Python3 Command Directly
This is the simplest and most common method. You call the Python interpreter followed by your script’s filename.
Assume you have a file named hello.py with this content:
print("Hello, Linux!")
Navigate to the directory containing your script:
cd /path/to/your/script
Then run it:
python3 hello.py
You’ll see the output: Hello, Linux!
That’s it. The interpreter reads each line and executes it. You can run any Python file this way.
Pro tip: If you have multiple Python versions, use python3.11 or python3.10 to target a specific version.
Method 2: Making The Script Executable
You can run a Python script like any other program. This requires two steps: adding a shebang line and setting execute permissions.
First, add this as the very first line of your script:
#!/usr/bin/env python3
This tells the system to use the Python3 interpreter. Your script now looks like:
#!/usr/bin/env python3
print("Hello, Linux!")
Second, make the file executable:
chmod +x hello.py
Now you can run it directly:
./hello.py
Notice you don’t need to type python3 anymore. The system uses the shebang to find the interpreter.
This method is ideal for scripts you use often. It feels more natural, like running any Linux command.
Method 3: Running Python Script With Arguments
Many scripts accept command-line arguments. Python makes this easy with the sys module.
Create a script called greet.py:
#!/usr/bin/env python3
import sys
name = sys.argv[1]
print(f"Hello, {name}!")
Make it executable and run it with an argument:
./greet.py Alice
Output: Hello, Alice!
You can pass multiple arguments. They are stored in sys.argv as a list. The first element (sys.argv[0]) is always the script name.
For more complex argument parsing, use the argparse module. It’s built into Python and handles flags, options, and help text.
Method 4: Running Python Script In Background
Sometimes you want a script to keep running even after you close the terminal. This is common for servers or long-running tasks.
Use the ampersand (&) to run the script in the background:
python3 myscript.py &
The script runs, and you get your terminal prompt back. You can check its status with:
jobs
To bring it back to the foreground, use:
fg %1
For scripts that must survive terminal closure, use nohup:
nohup python3 myscript.py &
This ignores the hangup signal. Output goes to nohup.out by default. You can redirect it:
nohup python3 myscript.py > output.log 2>&1 &
Now your script runs even if you log out.
Method 5: Using The Python Interactive Shell
For quick tests, you don’t need a file at all. Just type python3 in the terminal to enter the interactive shell.
You’ll see the Python prompt (>>>). Type your code line by line:
>>> print("Hello")
Hello
Exit with exit() or Ctrl+D.
This is perfect for testing small snippets or debugging. But for real scripts, always use a file.
Common Errors And How To Fix Them
You might hit some roadblocks. Here are the most frequent issues and solutions.
Error: “Python3: Command Not Found”
Python isn’t installed or not in your PATH. Install it using your package manager as shown earlier.
Error: “Permission Denied”
You tried to run ./script.py but it’s not executable. Fix it:
chmod +x script.py
Error: “SyntaxError”
Check your Python code. Common causes: missing colons, indentation issues, or using Python 2 syntax with Python 3.
Error: “ModuleNotFoundError”
Your script imports a module that isn’t installed. Install it with pip:
pip3 install module_name
If you get “pip: command not found”, install pip:
sudo apt install python3-pip
Best Practices For Running Python Scripts On Linux
Follow these tips to make your workflow smoother and avoid common pitfalls.
Use Virtual Environments
Virtual environments keep project dependencies isolated. This prevents conflicts between different projects.
Create one:
python3 -m venv myenv
Activate it:
source myenv/bin/activate
Your prompt changes to show the environment name. Now install packages with pip. They stay inside this environment.
To deactivate:
deactivate
Always use virtual environments for serious projects.
Use Shebang Lines Correctly
Always use #!/usr/bin/env python3 instead of #!/usr/bin/python3. The env version finds Python in your PATH, which respects virtual environments.
Organize Your Scripts
Create a dedicated directory for your Python projects. Use descriptive filenames. Add comments to explain complex logic.
Test With Small Inputs First
Before running a script on real data, test it with small sample data. This catches bugs early.
Running Python Scripts With Cron (Scheduling)
You can automate Python scripts to run at specific times using cron. This is powerful for backups, reports, or system maintenance.
Edit your crontab:
crontab -e
Add a line like this to run a script every day at 2 AM:
0 2 * * * /usr/bin/python3 /home/username/scripts/backup.py
Use absolute paths for both Python and your script. Redirect output to a log file:
0 2 * * * /usr/bin/python3 /home/username/scripts/backup.py >> /home/username/logs/backup.log 2>&1
Test your cron job by setting a time a few minutes in the future.
Running Python Scripts With Systemd (Services)
For scripts that should run as system services (like web servers), use systemd. This gives you start/stop/restart control and automatic restarts on failure.
Create a service file at /etc/systemd/system/myscript.service:
[Unit]
Description=My Python Script
After=network.target
[Service]
ExecStart=/usr/bin/python3 /path/to/script.py
Restart=always
User=yourusername
[Install]
WantedBy=multi-user.target
Then enable and start it:
sudo systemctl enable myscript.service
sudo systemctl start myscript.service
Check its status:
sudo systemctl status myscript.service
This is more robust than cron for long-running processes.
Debugging Python Scripts On Linux
When things go wrong, you need to debug. Here are effective techniques.
Use Print Statements
The simplest debugger. Add print() statements to check variable values and program flow.
Use Python’s Built-In Debugger (Pdb)
Insert this line where you want to pause:
import pdb; pdb.set_trace()
Run the script. Execution stops at that line. You can inspect variables, step through code, and continue.
Common pdb commands:
n(next line)c(continue)p variable(print variable)q(quit)
Check Log Files
If your script writes to log files, check them for errors. Use tail -f logfile to watch logs in real time.
Frequently Asked Questions
How do I run a Python script in the background in Linux?
Use python3 script.py & or nohup python3 script.py & to keep it running after you close the terminal.
Can I run a Python script without the .py extension?
Yes. The extension doesn’t matter. Just make sure the file has a shebang line and is executable. You can name it anything, like myscript.
What is the difference between python and python3 on Linux?
On most modern Linux systems, python points to Python 2 (if installed) and python3 points to Python 3. Always use python3 to avoid confusion.
How do I pass arguments to a Python script in Linux?
Add them after the script name: python3 script.py arg1 arg2. Inside the script, access them via sys.argv.
Why does my Python script run on Windows but not on Linux?
Common reasons: different file paths (use / instead of \), missing modules, case sensitivity (Linux is case-sensitive), or line ending issues. Use dos2unix to fix line endings.
Conclusion
You now know multiple ways to run Python scripts on Linux. Start with the simple python3 script.py method. As you get comfortable, use executable scripts and virtual environments.
Remember these key points:
- Always use
python3to avoid Python 2 issues - Use shebang lines for executable scripts
- Virtual environments keep your projects clean
- Cron and systemd help automate scripts
- Debug with print statements or pdb
Practice with small scripts first. Create a simple “Hello, World” and gradually add complexity. The more you run scripts, the more natural it becomes.
Linux gives you tremendous flexibility. You can run Python scripts from the terminal, schedule them, or turn them into system services. Each method has its place.
If you run into trouble, check the error messages carefully. They usually tell you exactly what’s wrong. And remember, the community is huge—almost every problem has been solved before.
Now go ahead and run your first Python script on Linux. You’ve got all the tools you need.