Home > Backend Development > Python Tutorial > How to Pass a String as stdin to subprocess.Popen?

How to Pass a String as stdin to subprocess.Popen?

Susan Sarandon
Release: 2024-12-06 13:04:12
Original
589 people have browsed it

How to Pass a String as stdin to subprocess.Popen?

Passing String Input to subprocess.Popen

The error encountered while attempting to pass a StringIO object as stdin to subprocess.Popen reveals that StringIO objects are not recognized as valid file-like objects by subprocess. To resolve this issue and successfully pass a string as stdin, it is necessary to first create a pipeline to the Popen process.

Using Explicit Pipeline Creation

The subprocess.communicate() documentation suggests creating a pipeline with stdin=PIPE to send data to the process's stdin. This can be achieved by modifying the code as follows:

import subprocess
from subprocess import Popen, PIPE, STDOUT

p = Popen(['grep', 'f'], stdout=PIPE, stdin=PIPE, stderr=STDOUT)
grep_stdout = p.communicate(input=b'one\ntwo\nthree\nfour\nfive\nsix\n')[0]
print(grep_stdout.decode())
Copy after login

This code creates a pipe to the grep process, allowing the input string to be passed through the stdin argument.

Using subprocess.run (Python 3.5 )

For Python versions 3.5 and higher, subprocess.run can be used to pass input as a string and retrieve the output as a string in a single call:

#!/usr/bin/env python3
from subprocess import run, PIPE

p = run(['grep', 'f'], stdout=PIPE,
        input='one\ntwo\nthree\nfour\nfive\nsix\n', encoding='ascii')
print(p.returncode)
print(p.stdout)
Copy after login

This approach provides a concise alternative to the explicit pipeline creation method.

The above is the detailed content of How to Pass a String as stdin to subprocess.Popen?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template