How to use subprocess command with pipes
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
If you want to reproduce a shell pipeline such as cmd1 | cmd2 in Python, the safest approach is to create separate subprocesses and connect the first process's stdout to the second process's stdin. Python's subprocess module supports this directly with Popen.
You can also use shell=True and pass the whole pipeline as a single string, but that is only appropriate for trusted commands. For general code, explicit pipes are safer and easier to control.
Build a Simple Two-Command Pipeline
The standard pattern is to create the first process with stdout=subprocess.PIPE, then pass that pipe as stdin to the next process.
This is the Python equivalent of:
Closing p1.stdout in the parent process is important because it lets the upstream process receive normal pipe behavior if the downstream process exits early.
A Longer Pipeline
You can chain more than two processes the same way.
This keeps the pipeline explicit, which is helpful when you need to inspect return codes or handle errors process by process.
When shell=True Is Acceptable
For a quick hardcoded command, you can let the shell build the pipeline.
This is shorter, but it should not be used with untrusted input. If any part of the command comes from a user, shell=True opens the door to shell injection.
Send Input into the First Process
Sometimes you want Python to provide the input rather than launching a command that generates it.
The general rule is to feed the input to the first process, then collect the final output from the last process.
Check Errors Explicitly
In a pipeline, the last command's success does not automatically tell you whether the earlier commands succeeded. Check return codes if correctness matters.
If you care about reliability, treat the whole pipeline as more than just the last command.
Prefer Python Logic When a Shell Pipeline Adds No Value
Sometimes the best answer is not to recreate the pipe at all. If you are only filtering lines, sorting data, or counting matches, Python may be clearer.
subprocess is most useful when you truly need existing command-line programs. Do not force everything through shell-style pipelines if a few lines of Python would be simpler and more portable.
Common Pitfalls
- Using
shell=Truewith user input and creating a shell injection risk. - Forgetting to close unused pipe ends in the parent process.
- Assuming only the last process's return code matters.
- Mixing bytes and text modes in a confusing way.
- Recreating a shell pipeline when pure Python would be simpler and easier to maintain.
Summary
- Use
subprocess.Popenwithstdout=subprocess.PIPEandstdin=previous.stdoutto build safe pipelines. - Reserve
shell=Truefor trusted, hardcoded commands. - Feed input to the first process and read output from the last process.
- Check return codes for the whole pipeline when correctness matters.
- Prefer plain Python over subprocess pipelines when no external command is actually needed.
Related reading
- How to use TensorFlow in OOP style?
- How to use TensorFlow metrics in Keras
- How to use tensorflow on spyder?
- How to use tf.nn.embedding_lookup_sparse in TensorFlow?
- How to use tf.reset_default_graph
- How to use tf.reset_default_graph
- How to use tf.while_loop in tensorflow
- How to use the AWS Python SDK while connecting via SSO credentials
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.