Executing a Python script in the Linux terminal requires navigating to its location and using the python3 command. If you are wondering how to run python script in linux terminal, the process is straightforward once you understand the basics. This guide walks you through every step, from checking your Python installation to running scripts with arguments, ensuring you can execute your code efficiently.
Linux is a powerful environment for Python development, and the terminal gives you full control. Whether you are a beginner or an experienced developer, mastering this skill will save you time and help you automate tasks. Let us start with the fundamentals and build up to advanced techniques.
Prerequisites For Running Python Scripts
Before you can run any Python script, you need to ensure Python is installed on your Linux system. Most distributions come with Python pre-installed, but you should verify this. Open your terminal and type the following command:
python3 --version
If Python is installed, you will see the version number, such as Python 3.10.12. If not, you will get an error message. In that case, install Python using your package manager. For Ubuntu or Debian-based systems, 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. Popular choices include:
- Nano (simple, terminal-based)
- Vim (powerful, but has a learning curve)
- VS Code (graphical, feature-rich)
- Gedit (lightweight, GUI-based)
Make sure you have basic knowledge of navigating the terminal using commands like cd, ls, and pwd. These will help you locate your script file.
How To Run Python Script In Linux Terminal
Now that your system is ready, let us focus on the core topic. The most common method to run a Python script is by using the python3 command followed by the script filename. Here is the basic syntax:
python3 script_name.py
Replace script_name.py with the actual name of your file. For example, if you have a script called hello.py, you would type:
python3 hello.py
This command tells the terminal to execute the Python interpreter and run the code inside hello.py. The script must be in your current working directory, or you need to provide the full path to it.
Step-By-Step Guide To Run Your First Script
Follow these numbered steps to run your first Python script in the Linux terminal:
- Open your terminal by pressing Ctrl + Alt + T or searching for “Terminal” in your applications.
- Create a new Python script using a text editor. For example, type: nano hello.py
- Write a simple Python command inside the file, such as: print(“Hello, Linux!”)
- Save the file. In Nano, press Ctrl + O, then Enter, then Ctrl + X to exit.
- Check that the file exists by typing: ls
- Run the script with: python3 hello.py
- You should see the output: Hello, Linux!
This process is the foundation for running any Python script. If you encounter errors, double-check the filename and ensure Python is installed correctly.
Using The Python Command Instead Of Python3
Some Linux systems might have the python command available instead of python3. This depends on your distribution and configuration. On older systems, python might point to Python 2, which is deprecated. To avoid confusion, always use python3 for Python 3 scripts. You can check which version python refers to by typing:
python --version
If it shows Python 3.x, you can use python instead. However, for consistency across different systems, stick with python3. This ensures your script runs on any modern Linux distribution.
Making Python Scripts Executable
Running a script with python3 script.py works fine, but you can also make the script directly executable. This allows you to run it like any other program, without typing python3 every time. The process involves two steps: adding a shebang line and setting execute permissions.
Adding A Shebang Line
The shebang is the first line of your script that tells the system which interpreter to use. For Python 3, it looks like this:
#!/usr/bin/env python3
Place this line at the very top of your script. For example, your hello.py file would start with:
#!/usr/bin/env python3
print("Hello, Linux!")
The /usr/bin/env part finds the Python interpreter automatically, making the script portable across different systems.
Setting Execute Permissions
After adding the shebang, you need to make the file executable. Use the chmod command:
chmod +x hello.py
Now you can run the script directly by typing:
./hello.py
The ./ tells the terminal to look in the current directory. If you move the script to a directory in your PATH, you can run it from anywhere without the ./ prefix.
Moving Scripts To PATH
To run your script from any location, move it to a directory like /usr/local/bin. For example:
sudo mv hello.py /usr/local/bin/hello
Notice that we removed the .py extension for simplicity. Now you can run it by just typing:
hello
This is useful for scripts you use frequently, like automation tools or custom utilities.
Running Python Scripts With Arguments
Many Python scripts accept command-line arguments to change their behavior. For example, you might pass a filename or a configuration option. The sys.argv list in Python captures these arguments. Here is how to pass them from the terminal:
python3 script.py arg1 arg2 arg3
Inside your script, you can access these arguments like this:
import sys
print(sys.argv)
This will print a list where the first element is the script name, followed by the arguments. For instance, running python3 test.py hello world outputs:
['test.py', 'hello', 'world']
Using Argparse For Better Argument Handling
For more complex scripts, use the argparse module. It provides help messages, type checking, and default values. Here is a simple example:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("name", help="Your name")
args = parser.parse_args()
print(f"Hello, {args.name}!")
Run it with:
python3 greet.py Alice
Output: Hello, Alice!
You can also add optional arguments with — flags. This makes your script more user-friendly and professional.
Running Python Scripts In The Background
Sometimes you want a script to run even after you close the terminal. This is useful for long-running tasks like web servers or data processing. You can run a script in the background by adding an ampersand (&) at the end:
python3 script.py &
The script runs in the background, and you get the terminal prompt back immediately. To bring it to the foreground, use the fg command. To see all background jobs, type:
jobs
If you want the script to keep running after you log out, use the nohup command:
nohup python3 script.py &
This ignores the hangup signal, so the script continues even if you close the terminal. Output is saved to a file called nohup.out by default.
Using Screen Or Tmux For Persistent Sessions
For more control, use terminal multiplexers like screen or tmux. These tools let you create sessions that persist even if your connection drops. To start a screen session:
screen -S mysession
Then run your script as usual. Detach from the session with Ctrl + A, then D. Reattach later with:
screen -r mysession
Tmux works similarly but uses different key bindings. Both are excellent for running scripts on remote servers.
Debugging Python Scripts In The Terminal
When your script does not work as expected, you need to debug it. The terminal offers several tools to help you find errors. The simplest method is to run the script and read the error messages. Python provides clear tracebacks that show where the error occured.
Using Print Statements
Add print() statements to check variable values and program flow. This is a quick and dirty method that works for small scripts. For example:
print(f"Debug: variable x is {x}")
Remove these lines once you fix the issue.
Using The Python Debugger (Pdb)
For more advanced debugging, use the built-in pdb module. Insert this line in your script where you want to pause:
import pdb; pdb.set_trace()
When the script reaches this line, it stops and gives you a (Pdb) prompt. You can then inspect variables, step through code, and continue execution. Common commands include:
- n (next line)
- c (continue)
- p variable (print variable)
- q (quit)
This is much more powerful than print statements and helps you understand complex bugs.
Running Scripts With Verbose Output
Some scripts have built-in logging or verbose modes. You can often enable these with command-line flags. For example, if your script uses the logging module, set the level to DEBUG:
python3 script.py --verbose
Check your script’s documentation for available options.
Common Errors And Solutions
Even experienced developers run into issues. Here are some frequent problems when running Python scripts in the terminal, along with fixes:
Command Not Found: Python3
If you see “python3: command not found”, Python is not installed or not in your PATH. Install it using your package manager as shown earlier. Alternatively, try python or python3.11 if you have multiple versions.
Permission Denied
This error occurs when you try to run a script directly without execute permissions. Use chmod +x script.py to fix it. If you are using the python3 command, you do not need execute permissions.
No Such File Or Directory
This means the script does not exist in your current directory. Use ls to list files and check the spelling. You can also use the full path, like:
python3 /home/user/scripts/hello.py
IndentationError Or SyntaxError
These are Python code errors. Check your script for incorrect indentation or typos. Use a text editor with syntax highlighting to spot issues easily.
Running Python Scripts From Different Directories
You do not always have to be in the same directory as your script. You can specify the full path to the script:
python3 /path/to/your/script.py
Alternatively, you can change to the script’s directory first:
cd /path/to/your/
python3 script.py
If your script imports modules from other files, it is often easier to run it from its own directory to avoid import errors. You can also add the script’s directory to Python’s sys.path, but that is more advanced.
Using Relative Paths
If your script is in a parent or child directory, use relative paths. For example, if you are in /home/user and the script is in /home/user/scripts, type:
python3 scripts/hello.py
To go up one level, use ../:
python3 ../scripts/hello.py
Automating Script Execution With Cron
Linux’s cron system lets you schedule scripts to run at specific times. This is perfect for backups, reports, or maintenance tasks. To edit your cron jobs, type:
crontab -e
Add a line like this to run a script every day at 2 AM:
0 2 * * * /usr/bin/python3 /home/user/scripts/backup.py
The format is: minute hour day month weekday command. Use full paths to both python3 and your script to avoid issues. Make sure the script has execute permissions if you run it directly.
Logging Cron Output
To capture output from cron jobs, redirect it to a log file:
0 2 * * * /usr/bin/python3 /home/user/scripts/backup.py >> /home/user/backup.log 2>&1
This appends standard output and errors to backup.log. Check this file if the script does not run as expected.
Using Virtual Environments
When working on multiple Python projects, virtual environments keep dependencies isolated. This prevents conflicts between different versions of libraries. To create and use a virtual environment:
- Create the environment: python3 -m venv myenv
- Activate it: source myenv/bin/activate
- Install packages with pip as needed
- Run your script as usual: python3 script.py
- Deactivate when done: deactivate
When the environment is active, the terminal prompt shows (myenv) before your username. This indicates you are using the isolated Python interpreter and libraries.
Running Scripts With Virtual Environment From Anywhere
If you want to run a script with a specific virtual environment without activating it first, use the full path to the environment’s Python interpreter:
/home/user/myenv/bin/python3 script.py
This is useful for cron jobs or scripts that need a specific environment.
Conclusion
Running Python scripts in the Linux terminal is a fundamental skill that opens up endless possibilities for automation and development. From the basic python3 command to making scripts executable, passing arguments, and scheduling tasks, you now have a comprehensive toolkit. Practice these methods regularly to become proficient. Remember to always use python3 for clarity, and do not hesitate to use debugging tools when things go wrong. The terminal is your friend, and with these techniques, you can harness its full power for your Python projects.
Frequently Asked Questions
What Is The Difference Between Python And Python3 In Linux?
On many Linux systems, python may refer to Python 2, which is outdated and no longer supported. python3 specifically runs Python 3, the current version. Always use python3 to avoid compatibility issues.
Can I Run A Python Script Without The .Py Extension?
Yes, you can rename the file to anything, like script or myapp. Just ensure it has a shebang line and execute permissions. Then run it with ./script or by placing it in your PATH.
How Do I Run A Python Script That Requires Root Privileges?
Use sudo before the command, like sudo python3 script.py. Be cautious, as root access can modify system files. Only do this if you trust the script and understand what it does.
Why Does My Script Run But Produce No Output?
Check if your script has print() statements or other output. If it uses logging, the output might go to a file. Also ensure there are no errors by running it with python3 -u script.py for unbuffered output.
Can I Run Python Scripts From A USB Drive Or External Storage?
Yes, navigate to the mount point of the drive using cd, then run the script as usual. Ensure the drive is mounted and you have read permissions. For scripts with dependencies, consider using a virtual environment on the drive.