Come faccio a passare una stringa in subprocess.Popen in Python 2? [duplicare]

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

  •  07-07-2019
  •  | 
  •  

Domanda

    

Questa domanda ha già una risposta qui:

         

Vorrei eseguire un processo da Python (2.4 / 2.5 / 2.6) usando Popen , e I vorrei dargli una stringa come input standard.

Scriverò un esempio in cui il processo esegue un " head -n 1 " il suo input.

Il seguente funziona, ma vorrei risolverlo in un modo migliore, senza usare echo :

>>> from subprocess import *
>>> p1 = Popen(["echo", "first line\nsecond line"], stdout=PIPE)
>>> Popen(["head", "-n", "1"], stdin=p1.stdout)
first line

Ho provato a usare StringIO , ma non funziona:

>>> from StringIO import StringIO
>>> Popen(["head", "-n", "1"], stdin=StringIO("first line\nsecond line"))
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "/usr/lib/python2.4/subprocess.py", line 533, in __init__
    (p2cread, p2cwrite,
  File "/usr/lib/python2.4/subprocess.py", line 830, in _get_handles
    p2cread = stdin.fileno()
AttributeError: StringIO instance has no attribute 'fileno'

Suppongo di poter creare un file temporaneo e scrivere la stringa lì - ma non è neanche molto carino.

È stato utile?

Soluzione

Hai provato a inserire la tua stringa in comunicare come una stringa?

Popen.communicate(input=my_input)

Funziona così:

p = subprocess.Popen(["head", "-n", "1"], stdin=subprocess.PIPE)
p.communicate('first\nsecond')

uscita:

first

Ho dimenticato di impostare stdin su subprocess.PIPE quando l'ho provato all'inizio.

Altri suggerimenti

Usa os.pipe :

>>> from subprocess import Popen
>>> import os, sys
>>> read, write = os.pipe()
>>> p = Popen(["head", "-n", "1"], stdin=read, stdout=sys.stdout)
>>> byteswritten = os.write(write, "foo bar\n")
foo bar
>>>
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top