杰瑞科技汇

Linux中Bash与Python到底该如何选择?

Linux, Bash, and Python form the "holy trinity" of modern system administration, DevOps, and backend development. They work together seamlessly: Linux is the operating system, Bash is the native language to control it, and Python is the high-level language used to build complex tools on top of it.

Linux中Bash与Python到底该如何选择?-图1
(图片来源网络,侵删)

Here is a breakdown of how they interact, how to use them together, and best practices.


The Golden Rule: When to use which?

  • Bash: Best for simple file manipulation, starting/stopping services, writing quick pipelines (grep | awk | sed), and executing sequential commands. If it takes less than 20 lines and doesn't need complex logic or data structures, use Bash.
  • Python: Best for APIs, web scraping, data parsing (JSON, YAML, CSV), complex math, and interacting with cloud services (AWS, Azure). If you need if/else statements, loops inside loops, or error handling, use Python.

How to use Python inside Bash

Often, you will write a Bash script but need Python to do the heavy lifting. You can execute Python commands directly from the terminal or a Bash script.

Single-line Python execution:

# Use the -c flag to run a Python command
python3 -c "import datetime; print(datetime.datetime.now())"

Passing Bash variables into Python:

Linux中Bash与Python到底该如何选择?-图2
(图片来源网络,侵删)
#!/bin/bash
FILENAME="data.txt"
PYTHON_OUTPUT=$(python3 -c "print(f'Processing {len(open('$FILENAME').readlines())} lines.')")
echo "$PYTHON_OUTPUT"

How to use Bash inside Python

Sometimes you are writing a Python script and just need to run a simple Linux command (like ls, ping, or grep).

The Modern Way (subprocess): Note: Never use os.system() in modern Python. Always use subprocess.

import subprocess
# Run a simple command
result = subprocess.run(["ls", "-l"], capture_output=True, text=True)
print(result.stdout)
# Run a command with a pipe (using shell=True)
result = subprocess.run("cat /var/log/syslog | grep error", shell=True, capture_output=True, text=True)
print(result.stdout)

Writing a "Hybrid" Script (The ultimate trick)

You can write a single file that acts as both a valid Bash script and a valid Python script. This is incredibly useful for distributing tools.

Create a file called hybrid_script:

Linux中Bash与Python到底该如何选择?-图3
(图片来源网络,侵删)
#!/bin/bash
"true" '''\'
# This part is interpreted by Bash
echo "Hello from Bash!"
echo "Passing control to Python..."
exec python3 "$0" "$@"
exit $?
'''
# This part is interpreted by Python
import sys
print(f"Hello from Python! You passed these arguments: {sys.argv[1:]}")

How it works: Bash sees "true" '''\' and ignores the Python code below it, then uses exec to hand the script over to Python. Python sees and treats the Bash code as a multi-line string, ignoring it.


Creating a Python Virtual Environment (Best Practice)

When working on Linux, it is bad practice to install Python packages globally (using sudo pip install). Instead, use a virtual environment.

# 1. Install python3-venv (Ubuntu/Debian)
sudo apt update
sudo apt install python3-venv
# 2. Create a virtual environment
python3 -m venv myenv
# 3. Activate it
source myenv/bin/activate
# 4. Now you can install packages safely
pip install requests
# 5. When you are done, deactivate it
deactivate

Useful Bash Aliases for Python Developers

Add these to your ~/.bashrc or ~/.zshrc file to speed up your workflow:

# Create and activate a virtual environment in one command
alias venv='python3 -m venv venv && source venv/bin/activate'
# Upgrade pip automatically
alias pipup='pip install --upgrade pip'
# Run Python HTTP server in current directory (great for sharing files)
alias serve='python3 -m http.server 8000'

What would you like to do next?

I can help you with:

  1. Writing a specific Bash script to automate a Linux task.
  2. Writing a Python script that interacts with Linux files or APIs.
  3. Explaining a specific Bash or Python command.
分享:
扫描分享到社交APP
上一篇
下一篇