Home >Backend Development >Python Tutorial >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!