Home >Backend Development >Python Tutorial >How to Correctly Pass Strings to `subprocess.Popen` via stdin?
Attempting to utilize StringIO with subprocess.Popen for stdin results in an AttributeError.
import subprocess from cStringIO import StringIO subprocess.Popen(['grep', 'f'], stdout=subprocess.PIPE, stdin=StringIO('one\ntwo\nthree\nfour\nfive\nsix\n')).communicate()[0]
Traceback highlights the incompatibility of cStringIO.StringIO with the fileno() method required by subprocess.Popen.
AttributeError: 'cStringIO.StringI' object has no attribute 'fileno'
The subprocess.Popen documentation requires using stdin=PIPE for data transmission to stdin. The os.popen() replacement syntax is recommended:
pipe = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE).stdin
Adapting the original code:
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()) # -> four # -> five # ->
For Python 3.5 :
#!/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) # -> 0 print(p.stdout) # -> four # -> five # ->
The above is the detailed content of How to Correctly Pass Strings to `subprocess.Popen` via stdin?. For more information, please follow other related articles on the PHP Chinese website!