Running a Python script on Linux is a fundamental skill for automating tasks and building applications. Knowing how to run python script linux can save you hours of manual work and open up endless possibilities for system automation. Whether you’re a beginner or an experienced developer, executing Python scripts on Linux is straightforward once you understand the basics. This guide will walk you through every method, from the simplest commands to advanced techniques like using virtual environments and scheduling scripts.
Python is pre-installed on most Linux distributions, so you can usually start right away. But there are multiple ways to run a script, depending on your needs. Let’s break it down step by step.
Prerequisites For Running Python On Linux
Before you run any script, make sure Python is installed. 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 Ubuntu or Debian, use:
sudo apt update && sudo apt install python3
For Fedora or CentOS, use:
sudo dnf install python3
You also need a text editor to write your script. Nano, Vim, or VS Code are popular choices. Create a simple test script called hello.py with this content:
print("Hello, Linux!")
Now you’re ready to learn the main methods.
How To Run Python Script Linux
The most common way is using the terminal. Navigate to the directory containing your script with the cd command. Then run:
python3 hello.py
This executes the script and prints “Hello, Linux!” to the terminal. The python3 command explicitly calls Python version 3. On some systems, python alone might point to Python 2, which is outdated. Always use python3 for clarity.
You can also run scripts from any location by providing the full path:
python3 /home/user/projects/hello.py
If your script is in the current directory, you can use a relative path like ./hello.py after making it executable. We’ll cover that next.
Making The Script Executable
To run a script like a command (without typing python3), you need to make 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:
chmod +x hello.py
Now you can run it directly:
./hello.py
This method is handy for scripts you use frequently. Just remember to include the shebang line every time.
Using The Python Interactive Shell
Sometimes you want to test small code snippets without creating a file. The interactive shell is perfect for that. Type python3 in the terminal to enter it. You’ll see a >>> prompt where you can type Python code line by line:
>>> print("Testing")
Testing
>>> 2 + 2
4
To exit, type exit() or press Ctrl+D. This is great for quick experiments, but for larger scripts, always use a file.
Running Scripts With Arguments
Many scripts accept command-line arguments. For example, a script that processes a file might need the filename as input. Create a script called args.py:
import sys
print("You passed:", sys.argv[1])
Run it with an argument:
python3 args.py myfile.txt
The output will be “You passed: myfile.txt”. Arguments are stored in sys.argv as a list. The first element is always the script name itself.
You can pass multiple arguments separated by spaces. For more complex argument parsing, use the argparse module.
Using Virtual Environments
When working on multiple projects, dependencies can clash. Virtual environments isolate project-specific packages. Create one with:
python3 -m venv myenv
Activate it:
source myenv/bin/activate
Your prompt will change to show the environment name. Now install packages with pip without affecting the system Python. To run a script inside the environment, just use python3 script.py while activated. Deactivate with:
deactivate
This is best practice for any serious Python development on Linux.
Running Scripts In The Background
Sometimes you want a script to keep running even after you close the terminal. Use the ampersand symbol:
python3 long_script.py &
This runs the script in the background. You’ll get a process ID (PID) you can use to stop it later with kill PID. To keep it running after logout, use nohup:
nohup python3 long_script.py &
Output will be saved to nohup.out unless you redirect it. This is useful for server scripts or data processing tasks.
Scheduling Scripts With Cron
Automate repetitive tasks by scheduling scripts with cron. Edit your crontab file:
crontab -e
Add a line to run a script every day at 2 AM:
0 2 * * * /usr/bin/python3 /home/user/script.py
The format is: minute, hour, day of month, month, day of week. Use full paths for both Python and the script to avoid issues. Check your script’s output by redirecting to a log file:
0 2 * * * /usr/bin/python3 /home/user/script.py >> /home/user/log.txt 2>&1
Cron is powerful but test your script manually first to ensure it works.
Debugging Common Issues
When you run a script, errors can happen. The most common is “Permission denied” — fix it with chmod +x. Another is “ModuleNotFoundError” — install the missing module with pip install module_name. If you see “SyntaxError”, check your Python version; Python 2 code won’t run with python3.
Use python3 -c "print('test')" to run one-liners for quick tests. For debugging, insert print() statements to see variable values, or use the pdb debugger:
python3 -m pdb script.py
This lets you step through code line by line.
Running Scripts With Different Python Versions
If you have multiple Python versions installed, use the specific version command. For Python 3.8, use python3.8. For Python 3.10, use python3.10. Check available versions with:
ls /usr/bin/python*
You can also use pyenv to manage multiple versions easily. This is advanced but useful for compatibility testing.
Using IDEs And Text Editors
While the terminal is powerful, many developers prefer IDEs like PyCharm or VS Code. These tools let you run scripts with a single click. In VS Code, open your script file and press Ctrl+F5 to run. The output appears in the integrated terminal. This is great for larger projects where you need debugging and code completion.
For quick edits, nano or vim in the terminal work fine. Just remember to save your file before running it.
Running Scripts From Other Languages
You can call Python scripts from Bash scripts or other programs. In a Bash script, just include the Python command:
#!/bin/bash
python3 /path/to/script.py
You can also pass variables from Bash to Python:
#!/bin/bash
VAR="Hello"
python3 -c "import sys; print(sys.argv[1])" "$VAR"
This flexibility makes Python a great tool for system automation.
Best Practices For Running Scripts
Always use python3 instead of python to avoid version confusion. Keep your scripts in a dedicated directory like ~/scripts and add it to your PATH if you use them often. Use virtual environments for projects with dependencies. Test scripts with sample data before running on real files.
Log output to files for long-running scripts so you can check results later. Use try-except blocks in your code to handle errors gracefully. And always backup important data before running scripts that modify files.
Running Scripts With Sudo
Some scripts need root privileges to access system resources. Run them with sudo:
sudo python3 script.py
Be careful — a typo in a script run with sudo can damage your system. Only use sudo when absolutely necessary, and review the script’s code first.
Conclusion
Running Python scripts on Linux is a skill that pays off quickly. From simple one-liners to complex automation, you now have the tools to execute any script. Start with the basic python3 script.py command, then explore making scripts executable, using arguments, and scheduling with cron. Practice with small scripts to build confidence, and soon you’ll be automating tasks like a pro.
Remember to always check your Python version, use virtual environments for projects, and test thoroughly. The Linux terminal is your friend — embrace it, and you’ll wonder how you ever worked without it.
Frequently Asked Questions
How Do I Run A Python Script In The Background On Linux?
Use the ampersand symbol: python3 script.py &. For persistent background execution, use nohup python3 script.py & to keep it running after logout.
What Is The Difference Between Python And Python3 On Linux?
On many systems, python points to Python 2 (which is deprecated), while python3 points to Python 3. Always use python3 to avoid compatibility issues.
Can I Run A Python Script Without Typing Python3 Every Time?
Yes. Add a shebang line (#!/usr/bin/env python3) at the top of your script, make it executable with chmod +x script.py, then run it with ./script.py.
How Do I Pass Command-line Arguments To A Python Script?
Include them after the script name: python3 script.py arg1 arg2. Inside the script, access them via sys.argv list.
What Should I Do If I Get A “ModuleNotFoundError” When Running A Script?
Install the missing module using pip: pip install module_name. If you’re using a virtual environment, activate it first before installing.