I'm a year and a half into my first DevOps role, and I find myself struggling with high-level languages for scripting and automation. Specifically, I want to know how people efficiently interact with machines without relying on Bash. For example, I want to write a script that stops a few systemd services, does something, and then starts them again. I've seen examples in Python, but most are tied to using DBus, which isn't intuitive for me. Is it common for folks to use Python for wider tasks like interacting with web APIs instead of system utilities? I'm also looking to write a command-line interface (CLI) to manage multiple software versions, and while I appreciate tools like Ansible, it's not quite what I need in this situation.
2 Answers
To translate your example into Python, you would typically use the subprocess module. You'd define a function that runs the systemctl commands, and it would look something like this:
```python
import subprocess
subprocess.run(['systemctl', 'stop', 'X', 'Y', 'Z'], check=True)
# do something
subprocess.run(['systemctl', 'start', 'X', 'Y', 'Z'], check=True)
```
This offers better error handling and can be expanded easily without making your script unwieldy.
Python really shines when your script becomes more complex than just a couple of Bash commands. It offers external modules, type hints, and better readability, which can shift your productivity into overdrive. Think of something like explainshell.com when you're wrestling with tricky Bash syntax—Python's syntax feels much closer to English, making it easier to write and maintain as projects grow.
That's a good point. But let's not pretend Python doesn’t have its pitfalls, like managing interpreters and packages. Sometimes a well-structured Bash script can age much better.
Totally agree! If your scripts are getting over a few dozen lines long, switching to Python or another suitable language just makes sense for maintainability.