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
Release: 2024-12-05 09:54:12
Original
564 people have browsed it

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]
Copy after login

Error

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

AttributeError: 'cStringIO.StringI' object has no attribute 'fileno'
Copy after login

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
Copy after login

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
# ->
Copy after login

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
# -> 
Copy after login

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template