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.

GG.
  • 21,083
  • 14
  • 84
  • 130
ducin
  • 25,621
  • 41
  • 157
  • 256
  • 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. – synthesizerpatel Aug 04 '13 at 22:50
  • @synthesizerpatel not an answer, but thanks for a valuable comment! – ducin Aug 05 '13 at 08:02
  • 1
    Well.. In fairness, it's **an** answer. Just not **the** answer. :D – synthesizerpatel Aug 05 '13 at 08:56

1 Answers1

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

AdamKG
  • 13,678
  • 3
  • 38
  • 46
  • You can also specify 'stdin=0', referencing the stdin file handle by numeric value as well. – synthesizerpatel Aug 04 '13 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 Aug 04 '13 at 23:22
  • Fair enough, just felt the use of file handle by number was worth mentioning. – synthesizerpatel Aug 04 '13 at 23:30
  • This answer warns of a deadlock with your approach http://stackoverflow.com/a/165662/1317713 – Leonid Sep 29 '15 at 16:44