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

后端 未结 11 3046
半阙折子戏
半阙折子戏 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条回答
  •  猫巷女王i
    2020-11-22 02:11

    There's a beautiful solution if you're using Python 3.4 or better. Use the input argument instead of the stdin argument, which accepts a bytes argument:

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

    This works for check_output and run, but not call or check_call for some reason.

提交回复
热议问题