Home >Backend Development >Python Tutorial >How to Correctly Pass String Input to `subprocess.Popen`'s stdin?

How to Correctly Pass String Input to `subprocess.Popen`'s stdin?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-19 06:04:51601browse

How to Correctly Pass String Input to `subprocess.Popen`'s stdin?

Passing String Input to Subprocess.Popen via Stdin

Problem:

Passing a string into the stdin argument of subprocess.Popen using a cStringIO.StringIO object results in an error, as the object lacks the necessary fileno attribute.

Solution:

To resolve this issue, it is recommended to use the more straightforward approach outlined in the Popen.communicate() documentation. By setting stdin=PIPE, you can create a pipe for stdin and provide the string input directly to the communicate method.

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())

# Output:
# -> four
# -> five
# ->

Additional Note:

For Python 3.5 (3.6 for encoding), subprocess.run simplifies the process by allowing you to pass string input and retrieve the output as a string in a single call.

from subprocess import run, PIPE

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

# Output:
# -> 0
print(p.stdout)

# Output:
# -> four
# -> five
# -> 

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

Statement:
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