Python-(stdin引数を使用して)文字列をsubprocess.Popenに渡す方法

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

  •  03-07-2019
  •  | 
  •  

質問

次の場合:

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'

明らかに、cStringIO.StringIOオブジェクトは、subprocess.Popenに適合するファイルダックに十分に近づきません。これを回避するにはどうすればよいですか?

役に立ちましたか?

解決

Popen.communicate() ドキュメント:

  

データを送信する場合は、   プロセスの標準入力である必要があります   Popenオブジェクトを作成します   stdin = PIPE。同様に、何かを取得するには   結果タプルのNone以外、   stdout = PIPEを指定する必要があります   stderr = PIPEも。

     

os.popen *の置換

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

警告ではなく、communicate()を使用します   stdin.write()、stdout.read()または   stderr.read()によるデッドロックの回避   他のOSパイプバッファへ   子供をいっぱいにしてブロックする   プロセス。

あなたの例は次のように書くことができます:

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

現在のPython 3バージョンでは、 subprocessを使用できます。 .run 。入力を文字列として外部コマンドに渡し、その終了ステータスを取得し、その出力を文字列として1回の呼び出しで返します。

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

他のヒント

この回避策を見つけました:

>>> 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()

もっと良いものはありますか?

パイプを作成することを誰も提案していないことに少し驚いています。これは、サブプロセスのstdinに文字列を渡す最も簡単な方法です。

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

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

Python 3.4以上を使用している場合は、美しい解決策があります。バイト引数を受け入れる stdin 引数の代わりに、 input 引数を使用します。

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

python3を使用していますが、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)

&quot;どうやらcStringIO.StringIOオブジェクトはsubprocess.Popen&quot;に合うようにファイルダックに十分に近づいていません

:-)

私は怖くない。パイプは低レベルのOSの概念であるため、OSレベルのファイル記述子で表されるファイルオブジェクトが絶対に必要です。回避策は正しいものです。

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()

s が大きすぎる場合、 Popen.communicate(input = s)が問題を引き起こす可能性があることに注意してください。 / em>子サブプロセスをフォークします。つまり、「2倍」必要です。その時点でメモリを使用していました(少なくとも「フードの下」の説明とこちらにあるリンクされたドキュメントによる)。私の特定のケースでは、 s は最初に完全に展開されてから stdin に書き込まれるジェネレーターであったため、子プロセスが生成される直前に親プロセスは巨大でした。 フォークするためのメモリが残っていませんでした:

File&quot; /opt/local/stow/python-2.7.2/lib/python2.7/subprocess.py"、1130行目、_execute_child     self.pid = os.fork() OSError:[Errno 12]メモリを割り当てることができません

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)
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top