10

I've got a main process in which I run a subprocess, which stdin is what I want to pipe. I know I can do it using files:

import subprocess
subprocess.call('shell command', stdin=open('somefile','mode'))

Is there any option to use a custom stdin pipe WITHOUT actual hard drive files? Is there any option, for example, to use string list (each list element would be a newline)?

I know that python subprocess calls .readline() on the pipe object.

3
  • 1
    While not necessarily the answer to your question, it's worth mentioning that any POSIX compliant operating system supports the use of /dev/stdin as a 'file', this works across the board with shell commands using an EOF for terminating the stream. Just verified this using tcsh and bash on OSX, Linux and OpenBSD. Commented Aug 4, 2013 at 22:50
  • @synthesizerpatel not an answer, but thanks for a valuable comment!
    – ducin
    Commented Aug 5, 2013 at 8:02
  • 1
    Well.. In fairness, it's an answer. Just not the answer. :D Commented Aug 5, 2013 at 8:56

1 Answer 1

6

First, use subprocess.Popen - .call is just a shortcut for it, and you'll need to access the Popen instance so you can write to the pipe. Then pass subprocess.PIPE flag as the stdin kwarg. Something like:

import subprocess
proc = subprocess.Popen('shell command', stdin=subprocess.PIPE)
proc.stdin.write("my data")

http://docs.python.org/2/library/subprocess.html#subprocess.PIPE

4
  • You can also specify 'stdin=0', referencing the stdin file handle by numeric value as well. Commented Aug 4, 2013 at 22:51
  • @synthesizerpatel er, it's a subtle difference, but that's telling the subprocess to use the parent process' stdin - not what was asked, where the data that's being piped in was (in his example) generated from a list of strings. Apart from that, I'd discourage passing fd-number-handles in general (as well as /dev/stdin), except and unless 'proxying' the data in-process is too shown to be too slow in a benchmark. The reason is that shared stdin, sooner or later, will cause bugs when the wrong process does the reading, and messes up the data stream for the intended stdin-handling process.
    – AdamKG
    Commented Aug 4, 2013 at 23:22
  • Fair enough, just felt the use of file handle by number was worth mentioning. Commented Aug 4, 2013 at 23:30
  • This answer warns of a deadlock with your approach stackoverflow.com/a/165662/1317713
    – Leonid
    Commented Sep 29, 2015 at 16:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.