Python - Come posso passare una stringa in subprocess.Popen (usando l'argomento stdin)?

StackOverflow https://stackoverflow.com/questions/163542

  •  03-07-2019
  •  | 
  •  

Domanda

Se faccio quanto segue:

import subprocess
from cStringIO import StringIO
subprocess.Popen(['grep','f'],stdout=subprocess.PIPE,stdin=StringIO('one\ntwo\nthree\nfour\nfive\nsix\n')).communicate()[0]

Ottengo:

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'

Apparentemente un oggetto cStringIO.StringIO non si restringe abbastanza vicino a un file duck per adattarsi a subprocess.Popen. Come aggirare questo problema?

È stato utile?

Soluzione

Popen.communicate () documentazione:

  

Nota che se vuoi inviare dati a   lo stdin del processo, è necessario   crea l'oggetto Popen con   stdin = TUBO. Allo stesso modo, per ottenere qualsiasi cosa   diverso da Nessuno nella tupla risultante,   devi dare stdout = PIPE e / o   stderr = PIPE too.

     

Sostituzione di os.popen *

    pipe = os.popen(cmd, 'w', bufsize)
    # ==>
    pipe = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE).stdin
  

Avviso Usa communic () anziché   stdin.write (), stdout.read () o   stderr.read () per evitare deadlock dovuti   a uno qualsiasi degli altri buffer di pipe del sistema operativo   riempiendo e bloccando il bambino   processo.

Quindi il tuo esempio potrebbe essere scritto come segue:

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

Nell'attuale versione di Python 3, è possibile utilizzare subprocess .run , per passare l'input come stringa a un comando esterno e ottenere il suo stato di uscita e il suo output come stringa indietro in una chiamata:

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

Altri suggerimenti

Ho capito questa soluzione alternativa:

>>> p = subprocess.Popen(['grep','f'],stdout=subprocess.PIPE,stdin=subprocess.PIPE)
>>> p.stdin.write(b'one\ntwo\nthree\nfour\nfive\nsix\n') #expects a bytes type object
>>> p.communicate()[0]
'four\nfive\n'
>>> p.stdin.close()

Ce n'è uno migliore?

Sono un po 'sorpreso che nessuno abbia suggerito di creare una pipe, che secondo me è il modo più semplice per passare una stringa allo stdin di un sottoprocesso:

read, write = os.pipe()
os.write(write, "stdin input here")
os.close(write)

subprocess.check_call(['your-command'], stdin=read)

C'è una bella soluzione se stai usando Python 3.4 o superiore. Utilizzare l'argomento input anziché l'argomento stdin , che accetta un argomento byte:

output = subprocess.check_output(
    ["sed", "s/foo/bar/"],
    input=b"foo",
)

Sto usando python3 e ho scoperto che devi codificare la tua stringa prima di poterla passare a stdin:

p = Popen(['grep', 'f'], stdout=PIPE, stdin=PIPE, stderr=PIPE)
out, err = p.communicate(input='one\ntwo\nthree\nfour\nfive\nsix\n'.encode())
print(out)

" Apparentemente un oggetto cStringIO.StringIO non si restringe abbastanza vicino a un file duck per adattarsi al sottoprocesso. Apri "

: -)

Temo di no. La pipe è un concetto di sistema operativo di basso livello, quindi richiede assolutamente un oggetto file che è rappresentato da un descrittore di file a livello di sistema operativo. La soluzione alternativa è quella giusta.

from subprocess import Popen, PIPE
from tempfile import SpooledTemporaryFile as tempfile
f = tempfile()
f.write('one\ntwo\nthree\nfour\nfive\nsix\n')
f.seek(0)
print Popen(['/bin/grep','f'],stdout=PIPE,stdin=f).stdout.read()
f.close()
"""
Ex: Dialog (2-way) with a Popen()
"""

p = subprocess.Popen('Your Command Here',
                 stdout=subprocess.PIPE,
                 stderr=subprocess.STDOUT,
                 stdin=PIPE,
                 shell=True,
                 bufsize=0)
p.stdin.write('START\n')
out = p.stdout.readline()
while out:
  line = out
  line = line.rstrip("\n")

  if "WHATEVER1" in line:
      pr = 1
      p.stdin.write('DO 1\n')
      out = p.stdout.readline()
      continue

  if "WHATEVER2" in line:
      pr = 2
      p.stdin.write('DO 2\n')
      out = p.stdout.readline()
      continue
"""
..........
"""

out = p.stdout.readline()

p.wait()

Attenzione che Popen.communicate (input = s) potrebbe creare problemi se s è troppo grande, perché apparentemente il processo genitore lo bufferizzerà prima di biforcando il sottoprocesso figlio, il che significa che ha bisogno di "il doppio di" memoria utilizzata a quel punto (almeno secondo la spiegazione "sotto il cofano" e la documentazione collegata trovata qui ). Nel mio caso particolare, s era un generatore che era stato inizialmente completamente espanso e solo successivamente scritto in stdin quindi il processo genitore era enorme proprio prima che il bambino fosse generato, e non è rimasta memoria per bucarla:

File " /opt/local/stow/python-2.7.2/lib/python2.7/subprocess.py" ;, riga 1130, in _execute_child     self.pid = os.fork () OSError: [Errno 12] Impossibile allocare memoria

p = Popen(['grep', 'f'], stdout=PIPE, stdin=PIPE, stderr=STDOUT)    
p.stdin.write('one\n')
time.sleep(0.5)
p.stdin.write('two\n')
time.sleep(0.5)
p.stdin.write('three\n')
time.sleep(0.5)
testresult = p.communicate()[0]
time.sleep(0.5)
print(testresult)
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top