Search code examples
pythonpython-3.xsubprocess

How do I pass a string into subprocess.run using stdin?


How do I pass a string "foo" to a program expecting it on stdin if I'm using Python's subprocess.run()?


Solution

  • Simplest possible example, send foo to cat and let it print to the screen:

    import subprocess
    
    subprocess.run(['cat'], input=b'foo\n')
    

    Notice that you need to send binary data and a carriage return.