Python is a versatile, user-friendly programming language that excels in string manipulation, analytics, and reporting. For this reason, many system administrators use Python to accomplish routine tasks but fall back on Bash for familiar and often rudimentary chores. It's a good combination, but why use Bash for some tasks and Python for others when you can use both?
[ Download A sysadmin's guide to Bash scripting. ]
Using Bash to run repetitive tasks or low-level system commands and then Python for further analysis or processing the output into a readable format is an excellent way to harness the strength of both of these languages. Fortunately, Python's subprocess module easily integrates Bash into your Python scripts.
To run the examples in this guide, you must install Python 3.5 or above. The subprocess module is a standard library in Python and does not require manual installation.
Subprocess module basics
The subprocess module contains several practical methods to run the Bash commands. The primary subprocess method you will use is run. With run, you can write any Bash command in single, double, or triple quotes as the first argument in the method. For example:
subprocess.run("ls")
If you want to capture the output, you can add the capture_output=True argument:
subprocess.run("ls", capture_output=True)
While there are many other useful methods with the subprocess library, this guide focuses only on the run method.
Note: if you are using macOS, you must add the shell=True argument to the run method.
For more information on the subprocess module, please visit the docs.
When to use Python's subprocess module
The subprocess module works best when running simple Bash commands inside your Python script. The subprocess module is limited with more complex Bash commands or if you need to create a new shell.
For example, getting an rsh command to work with subprocess is extremely difficult. If you have a long Bash command that you want to run in subprocess, you can enclose it in triple quotes. For instance:
subprocess.run('''ls -l | awk -v OFS='\t' 'BEGIN { printf "%s\t%s\n", "Name", "Size"} {print $9,$5}''')
However, the best way to run complicated Bash commands is to create a Bash script with your commands and then use the subprocess module to run it. Depending on what you want to do, you can capture the output and then continue processing it in Python.
proc = subprocess.run(["./sample_Bash.sh"], shell=True, capture_output=True)
Practical Python
Python and Bash make a great combination for the busy sysadmin. I've covered the basics of the subprocess module in this article. In my next article, I'll demonstrate some practical ways you can combine Python with Bash on your system.
[ Learn how to manage your Linux environment for success. ]
저자 소개
Nicole Lama is a first-generation Panamanian-American with a bachelor's in biomedical sciences and a master's in bioinformatics and computational biology. Since 2015, she has worked with academics, tech startups, and Fortune 500 companies to help meet their data extraction, transformation, mobilization, storage, analytics, and visualization needs. She specializes in Python, machine learning, and open source technology.
채널별 검색
오토메이션
기술, 팀, 인프라를 위한 IT 자동화 최신 동향
인공지능
고객이 어디서나 AI 워크로드를 실행할 수 있도록 지원하는 플랫폼 업데이트
오픈 하이브리드 클라우드
하이브리드 클라우드로 더욱 유연한 미래를 구축하는 방법을 알아보세요
보안
환경과 기술 전반에 걸쳐 리스크를 감소하는 방법에 대한 최신 정보
엣지 컴퓨팅
엣지에서의 운영을 단순화하는 플랫폼 업데이트
인프라
세계적으로 인정받은 기업용 Linux 플랫폼에 대한 최신 정보
애플리케이션
복잡한 애플리케이션에 대한 솔루션 더 보기
가상화
온프레미스와 클라우드 환경에서 워크로드를 유연하게 운영하기 위한 엔터프라이즈 가상화의 미래