Home >Backend Development >Python Tutorial >How to Correctly Pass Strings to `subprocess.Popen` via stdin?

How to Correctly Pass Strings to `subprocess.Popen` via stdin?

DDD
DDDOriginal
2024-12-05 09:54:12566browse

How to Correctly Pass Strings to `subprocess.Popen` via stdin?

Passing Strings to subprocess.Popen via stdin

Problem

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]

Error

Traceback highlights the incompatibility of cStringIO.StringIO with the fileno() method required by subprocess.Popen.

AttributeError: 'cStringIO.StringI' object has no attribute 'fileno'

Solution

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

Example

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
# ->

Python 3.5 Solution

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!

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