How do I pass a string into subprocess.Popen (using the stdin argument)?

后端 未结 11 2973
半阙折子戏
半阙折子戏 2020-11-22 01:33

If I do the following:

import subprocess
from cStringIO import StringIO
subprocess.Popen([\'grep\',\'f\'],stdout=subprocess.PIPE,stdin=StringIO(\'one\\ntwo\\         


        
11条回答
  •  独厮守ぢ
    2020-11-22 02:07

    I figured out this workaround:

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

    Is there a better one?

提交回复
热议问题