Linux How To Run Python Script

Linux How To Run Python Script

Reading time1 min
#Linux#Python#Automation#Python3#Cron#Systemd

Mastering Python Script Execution in Linux: From Command Line to Automation

Most guides stop at a simple python script.py—let’s break that down and go beyond. In this post, you'll learn not only how to run Python scripts in Linux efficiently but also how to optimize your execution environment, manage dependencies seamlessly, and automate tasks like a seasoned Linux pro.

Whether you’re a developer, sysadmin, or tech enthusiast, understanding these concepts will empower you to leverage the full power and flexibility of Linux combined with Python's versatility.


Why Run Python Scripts in Linux?

Linux is widely regarded for its robustness and extensive tooling in software development and system administration. Python is the go-to language for automation, data processing, web development, and beyond. Running Python scripts effectively on Linux can streamline your workflows and increase productivity.


1. Basic Script Execution

The most straightforward way to run a Python script named hello.py is:

python hello.py

or (if your system defaults to Python 2):

python3 hello.py

Adding Shebang to Run Scripts Directly

You don’t need to prepend python every time if you add a shebang on top of your script.

#!/usr/bin/env python3
print("Hello from my script!")

Save this as hello.py, then make it executable:

chmod +x hello.py
./hello.py

This method treats your script like any executable file—handy for quick runs.


2. Handling Multiple Python Versions

Many Linux distributions come with Python 2.x and Python 3.x installed simultaneously. To be explicit about which Python interpreter runs your script:

python3 myscript.py   # Ensures you use Python 3 interpreter

You can check available versions with:

which python
which python3
python --version
python3 --version

3. Optimizing Execution Environment with Virtual Environments (venv)

Managing dependencies across projects can be messy if all libraries install globally. Virtual environments isolate project dependencies:

Create a virtual environment:

python3 -m venv myproject_env

Activate it:

source myproject_env/bin/activate

Now install packages locally without affecting the global environment:

pip install requests flask numpy

Run your script inside this environment simply as:

python myscript.py

When done:

deactivate

This prevents version conflicts and keeps your system clean.


4. Passing Arguments to Your Script

Often scripts take command-line arguments for flexibility. Here's an example script (greet.py):

import sys

if len(sys.argv) < 2:
    print("Usage: ./greet.py [name]")
else:
    print(f"Hello, {sys.argv[1]}!")

Run with arguments:

./greet.py Alice
# Output: Hello, Alice!

Alternatively, use more sophisticated parsing with argparse for user-friendly CLI interfaces.


5. Automating Script Execution: Using Cron Jobs

The real power comes when you automate repetitive tasks. Suppose you have a backup script backup.py you want running every day at midnight.

First, make sure your script runs independently (with shebang or directly via python).

Edit the cron jobs with:

crontab -e

Add this line for daily midnight run:

0 0 * * * /usr/bin/python3 /path/to/backup.py >> /path/to/backup.log 2>&1
  • Make sure to use absolute paths.
  • Redirect output to log for debugging.

Save and exit; Cron will now run your script automatically!


6. Using Systemd Timers for More Control (Optional)

For more robust scheduling than cron (with logging & dependency management), use systemd timers—a standard on most modern distros.

Create two files in ~/.config/systemd/user/ or /etc/systemd/system/:

  • myscript.service
  • myscript.timer

Example myscript.service:

[Unit]
Description=Run my Python backup script

[Service]
Type=oneshot
ExecStart=/usr/bin/python3 /path/to/backup.py

Example myscript.timer:

[Unit]
Description=Run backup daily at midnight

[Timer]
OnCalendar=daily

[Install]
WantedBy=timers.target

Enable & start timer with:

systemctl --user enable myscript.timer   
systemctl --user start myscript.timer  

This method provides precise control over when/how jobs run, with better integration into Linux startup/shutdown sequences.


7. Logging and Debugging Tips

Python scripts executed from CLI or automation tools often run without interactive feedback. Implement logging inside your scripts for easier debugging:

Sample logging setup (logging_example.py):

import logging

logging.basicConfig(filename='/tmp/myapp.log',
                    level=logging.INFO,
                    format='%(asctime)s %(levelname)s:%(message)s')

logging.info('Script started')
try:
    # Your code here...
    logging.info('Processing completed successfully')
except Exception as e:
    logging.error(f'Error occurred: {e}')

When automated via cron or systemd, check logs regularly or tailor alerting mechanisms by email or monitoring tools.


Final Thoughts

Running Python scripts on Linux is far more than calling python xyz.py. With proper setup—including shebang lines for executable scripts, virtual environments for dependency management, argument handling for flexibility, plus scheduled automation through cron or systemd—you can become highly efficient at leveraging both Linux’s power and Python's versatility.

Experiment by turning everyday manual tasks into automated workflows—you’ll free up time, reduce human error, and gain true mastery of scripting in a professional Linux environment.


Ready to Play?

Try this now by creating a simple script that prints disk usage stats (disk_usage.py):

#!/usr/bin/env python3

import subprocess

def get_disk_usage():
    result = subprocess.run(['df', '-h'], capture_output=True, text=True)
    print(result.stdout)

if __name__ == "__main__":
    get_disk_usage()

Make executable:

chmod +x disk_usage.py 
./disk_usage.py 

Schedule it daily via cron or systemd—your system admin self will thank you!


Feel free to ask if you'd like me to cover specific automation use-cases or dive deeper into advanced scripting techniques!