Home >Backend Development >Python Tutorial >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 # ->
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 # ->
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!