How to run a Python script in Linux

Running Python scripts on Linux is a fundamental skill. This guide covers methods from simple command-line invocation to advanced scheduling and service management, ensuring your Python code runs reliably and automatically.

1. Command-Line Invocation

Use the Python interpreter explicitly:

python3 /path/to/script.py
  

Or, if python maps to Python 3:

python script.py
  
Note: Confirm your Python version: python3 --version.

2. Using a Shebang and Executable Permissions

Add a shebang line at the top of script.py:

#!/usr/bin/env python3

print("Hello, Linux!")
  

Make it executable and run directly:

chmod +x script.py
./script.py
  
Place scripts in ~/bin or a directory in $PATH for global access.

3. Virtual Environments

Isolate dependencies using venv:

python3 -m venv myenv
source myenv/bin/activate
pip install -r requirements.txt
python script.py
deactivate
  
Note: Include the shebang pointing to the virtualenv’s Python for standalone executables:
#!./myenv/bin/python
  

4. Scheduling with Cron

Automate execution via cron:

# Edit crontab
crontab -e

# Run daily at 2AM
0 2 * * * /usr/bin/python3 /path/to/script.py >> /var/log/script.log 2>&1
  
Redirect output and errors to log files for troubleshooting.

5. Running as a Systemd Service

Create a service file /etc/systemd/system/myscript.service:

[Unit]
Description=My Python Script Service
After=network.target

[Service]
Type=simple
User=ubuntu
WorkingDirectory=/home/ubuntu
ExecStart=/usr/bin/python3 /home/ubuntu/script.py
Restart=on-failure

[Install]
WantedBy=multi-user.target
    

Enable and start the service:

sudo systemctl daemon-reload
sudo systemctl enable myscript
sudo systemctl start myscript
  

6. Running in Background with nohup or &

Detached execution:

nohup python3 script.py > script.out 2>&1 &
# or
python3 script.py > script.out 2>&1 &
  
Note: Use jobs and fg to manage background jobs in your shell.

7. Summary Checklist

  1. Run directly: python3 script.py.
  2. Make executable with shebang and chmod +x.
  3. Use virtual environments for dependency isolation.
  4. Schedule with cron for periodic tasks.
  5. Manage as a systemd service for resilience.
  6. Run in background using nohup or shell job control.
See also  How to uninstall Numpy?