An error occurs when passing a string to subprocess.Poven using the stdin factor.

Asked 2 years ago, Updated 2 years ago, 90 views

import subprocess
from cStringIO import StringIO
subprocess.Popen(['grep','f'],stdout=subprocess.PIPE,stdin=StringIO('one\ntwo\nthree\nfour\nfive\nsix\n')).communicate()[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "/build/toolchain/mac32/python-2.4.3/lib/python2.4/subprocess.py", line 533, in __init__
    (p2cread, p2cwrite,
  File "/build/toolchain/mac32/python-2.4.3/lib/python2.4/subprocess.py", line 830, in _get_handles
    p2cread = stdin.fileno()
AttributeError: 'cStringIO.StringI' object has no attribute 'fileno'

In subprocess.Popen, stdin=StringIO... I think there is an error because of this part, what should I do?

python subprocess stdin

2022-09-22 22:13

1 Answers

To briefly summarize Popen.communicate()

To transfer data to stdin of the process, you must create a Poen object using stdin=PIPE. To avoid deadlocks, we recommend using community() rather than stdin.write().

pipe = os.popen(cmd, 'w', bufsize)
Change # to the bottom
pipe = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE).stdin

So the code of the person who asked the question can be changed like this.

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


2022-09-22 22:13

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.