Home > Backend Development > Python Tutorial > How to Pass Strings to `subprocess.Popen` and `subprocess.run` in Python?

How to Pass Strings to `subprocess.Popen` and `subprocess.run` in Python?

Mary-Kate Olsen
Release: 2024-12-06 07:50:11
Original
1076 people have browsed it

How to Pass Strings to `subprocess.Popen` and `subprocess.run` in Python?

Passing Strings to subprocess.Popen through stdin

In order to pass a string to subprocess.Popen, it is essential to specify stdin=PIPE in the function call. This enables the stdin attribute of the Popen object to be a file-like object that can receive data from a string.

To demonstrate this, the following example could be implemented:

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

By providing stdin=PIPE, the input string can be passed to the grep process through stdin.communicate(), allowing for the processing of the input data and retrieval of the command's output.

Python 3.5 and later versions provide the subprocess.run function, which simplifies the process of passing strings to external commands and retrieving their outputs. This can be illustrated as follows:

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

By using subprocess.run, the input string can be directly passed as an argument to the input parameter, making data communication more straightforward.

The above is the detailed content of How to Pass Strings to `subprocess.Popen` and `subprocess.run` in Python?. 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