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
Release: 2024-12-19 06:04:51
Original
612 people have browsed it

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.

1

2

3

4

5

6

7

8

9

10

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

# ->

Copy after login

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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

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

# ->

Copy after login

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!

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