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

后端 未结 11 2781
半阙折子戏
半阙折子戏 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 01:55

    On Python 3.7+ do this:

    my_data = "whatever you want\nshould match this f"
    subprocess.run(["grep", "f"], text=True, input=my_data)
    

    and you'll probably want to add capture_output=True to get the output of running the command as a string.

    On older versions of Python, replace text=True with universal_newlines=True:

    subprocess.run(["grep", "f"], universal_newlines=True, input=my_data)
    

提交回复
热议问题