If you leave out "stream" it'll be stdin
432109
function(dbOrUri, stream, callback) {
    var db;
    if (arguments.length === 2) {
      callback = stream;
      stream = undefined;
    }
    if (!stream) {
      stream = process.stdin;
    }

    var state = 'start';
    var version;
    var collection;
    var endOfCollection;
    var insertQueue = [];
    var insertQueueSize = 0;

    // State machine

    var processors = {
      start: function(item, callback) {
        try {
          item = BSON.deserialize(item);
        } catch (e) {
          return callback(e);
        }
        if (typeof(item) !== 'object') {
          return callback(new Error('First BSON element is not an object'));
        }
        if (item.type !== 'mongo-dump-stream') {
          return callback(new Error('type property is not mongo-dump-stream'));
        }
        version = item.version;
        if (item.version > 2) {
          return callback(new Error('Incoming mongo-dump-stream is of a newer version, bailing out'));
        }
        endOfCollection = item.endOfCollection;
        state = 'collection';
        return callback(null);
      },
      collection: function(item, callback) {
        try {
          item = BSON.deserialize(item);
        } catch (e) {
          return callback(e);
        }
        if (item.type === 'endDatabase') {
          state = 'done';
          return callback(null);
        }
        if (item.type !== 'collection') {
          return callback(new Error('collection expected'));
        }
        var name = item.name;
        var indexes = item.indexes;
        async.series({
          create: function(callback) {
            return db.collection(name, function(err, _collection) {
              if (err) {
                return callback(err);
              }
              collection = _collection;
              return callback(null);
            });
          },
          indexes: function(callback) {
            return async.eachSeries(item.indexes, function(item, callback) {
              if (item.name === '_id_') {
                // automatic
                return setImmediate(callback);
              }
              return collection.ensureIndex(item.key, _.omit(item, 'ns', 'key'), callback);
            }, callback);
          }
        }, function(err) {
          if (err) {
            return callback(err);
          }
          state = 'documents';
          return callback(null);
        });
      },
      documents: function(item, callback) {
        if (version === '1') {
          item = BSON.deserialize(item);
          if (item.type === 'endCollection') {
            state = 'collection';
            return setImmediate(callback);
          }
          if (item.type !== 'document') {
            return callback(new Error('Document expected'));
          }
          return collection.insert(item.document, callback);
        }

        // Just scan for the unique random string that
        // appears in the end-of-collection object. No need
        // to waste time parsing BSON for this. Also
        // leverage the fact that it won't ever be
        // part of a large object to avoid scanning them all
        if (item.length < 100) {
          if (buffertools.indexOf(item, endOfCollection) !== -1) {
            return flush(function(err) {
              if (err) {
                return callback(err);
              }
              state = 'collection';
              return callback(null);
            });
          }
        }
        return async.series({
          flushIfNeeded: function(callback) {
            if (insertQueueSize + item.length <= 16777216) {
              return setImmediate(callback);
            }
            return flush(callback);
          },
          insertInQueue: function(callback) {
            insertQueueSize += item.length;
            insertQueue.push(item);
            return setImmediate(callback);
          }
        }, callback);

        function flush(callback) {
          if (!insertQueue.length) {
            // MongoDB considers it an error to be asked
            // to insert 0 documents ):
            return setImmediate(callback);
          }
          // watch out for race condition
          var insert = insertQueue;
          insertQueue = [];
          insertQueueSize = 0;
          return collection.insert(insert, function(err) {
            insertQueue = [];
            return callback(err);
          });
        }
      }
    };

    return async.series({
      connect: function(callback) {
        if (typeof(dbOrUri) !== 'string') {
          // Already a mongodb connection
          db = dbOrUri;
          return setImmediate(callback);
        }
        return mongodb.MongoClient.connect(dbOrUri, function(err, _db) {
          if (err) {
            return callback(err);
          }
          db = _db;
          return callback(null);
        });
      },
      dropCollections: function(callback) {
        return db.collections(function(err, collections) {
          if (err) {
            return callback(err);
          }
          return async.eachSeries(collections, function(item, callback) {
            if (item.collectionName.match(/^system\./)) {
              return setImmediate(callback);
            }
            return item.drop(callback);
          }, callback);
        });
      },
      loadCollections: function(finalCallback) {
        return reader({ raw: true, from: stream }, function(doc, callback) {
          return processors[state](doc, function(err) {
            if (err) {
              return callback(err);
            }
            if (state === 'done') {
              return finalCallback(null);
            }
            return callback(null);
          });
        }, function(err) {
          if (err) {
            return finalCallback(err);
          }
          return finalCallback(new Error('Premature end of stream'));
        });
      }
    }, callback);
  }
620243
def run(self):
    """"""
    if platform.system() == 'Windows':
      # Windows doesn't support file-like objects for select(), so fall back
      # to raw_input().
      response = input(''.join((self._message,
                                os.linesep,
                                PROMPT)))
      self._answered = True
      self._callback(response)
      return

    # First, display the prompt to the console.
    console_output.cli_print(self._message, color=self._color,
                             end=os.linesep, logger=None)
    console_output.cli_print(PROMPT, color=self._color, end='', logger=None)
    sys.stdout.flush()

    # Before reading, clear any lingering buffered terminal input.
    termios.tcflush(sys.stdin, termios.TCIFLUSH)

    line = ''
    while not self._stop_event.is_set():
      inputs, _, _ = select.select([sys.stdin], [], [], 0.001)
      if sys.stdin in inputs:
        new = os.read(sys.stdin.fileno(), 1024)
        if not new:
          # Hit EOF!
          # They hit ^D (to insert EOF). Tell them to hit ^C if they
          # want to actually quit.
          print('Hit ^C (Ctrl+c) to exit.')
          break
        line += new.decode('utf-8')
        if '\n' in line:
          response = line[:line.find('\n')]
          self._answered = True
          self._callback(response)
          return
1114988
def run(self, instream=sys.stdin):
        
        sys.stdout.write(self.prompt)
        sys.stdout.flush()
        while True:
            line = instream.readline()
            try:
                self.exec_cmd(line)
            except Exception as e:
                self.errfun(e)

            sys.stdout.write(self.prompt)
            sys.stdout.flush()
1218525
def getinputencoding(stream=None):
    
    if stream is None:
        stream = sys.stdin
    encoding = stream.encoding
    if not encoding:
        encoding = getpreferredencoding()
    return encoding
588
def process_stdin(line):
    ''''''
    if line is None:
        sys.exit(0)

    line = line.strip()
    if not line:
        return

    args = shlex.split(line)
    cmd = args[0]
    if cmd == 'help':
        k = command_map.keys()
        k.sort()
        for cmd in k:
            (fn, help) = command_map[cmd]
            print("%-15s : %s" % (cmd, help))
        return
    if cmd == 'exit':
        mestate.exit = True
        return

    if not cmd in command_map:
        print("Unknown command '%s'" % line)
        return
    (fn, help) = command_map[cmd]
    try:
        fn(args[1:])
    except Exception as e:
        print("ERROR in command %s: %s" % (args[1:], str(e)))
607736
def maybe_stream(s):
    """"""
    if isinstance(s, Stream):
        return s

    if s is None:
        stream = InMemStream()
        stream.close()  # we don't intend to write anything
        return stream

    if isinstance(s, unicode):
        s = s.encode('utf-8')
    if isinstance(s, bytearray):
        s = bytes(s)

    if isinstance(s, bytes):
        stream = InMemStream(s)
        stream.close()  # we don't intend to write anything
        return stream

    # s may still conform to the Stream interface. Yay duck typing.
    return s
1247634
def cli(ctx, amount, index, stage):
    """"""
    ctx.obj.say_green('Starting Streaming Pipe')
    res_pull = ctx.invoke(pull, amount=amount, index=index, stage=stage)
    res_tra = False
    if res_pull:
        # amount to transform can be less (or more)
        res_tra = ctx.invoke(
            transform, amount=amount, index=index, stage=stage)
    if res_tra:
        # amount to push can be less (or more)
        res_push = ctx.invoke(push, amount=amount, index=index, stage=stage)
    if res_pull and res_tra and res_push:
        ctx.obj.say_green('Streaming Pipe finsished')
        return True
    return False
293364
function(data) {
		//if (this.debug) console.log("Data: [" + data + "]");
		if (this.echo) process.stdout.write(data);
		this.instream = '' + this.instream + data.toString();

		for (;;) {		// peel off full lines of input containing JSON
			var m = this.instream.match(/\n/);
			if (!m) break;			// no more full lines
			var first_line = this.instream.slice(0, m.index + 1).trim();
			this.instream = this.instream.slice(m.index + 1);

			//if (this.debug) console.log('Line:', [first_line], [this.instream]);

			if (first_line.match(this.prompt)) {
				this.sendReply();
				first_line = first_line.slice(this.promptlength);
				this.instream = first_line + '\n' + this.instream;	// push back command text
				continue;
			}

			if (first_line.charAt(0) == '{') {			// detect JSON update sent by Bitlash
				var json_payload = JSON.parse(first_line);
				//console.log('JSON upstream:', json_payload);
				if (this.json_callback) this.json_callback(json_payload);
			}
			else this.reply.push(first_line);
		}

		// detect prompt indicating last command is complete
		if (this.instream.match(this.prompt)) {
			this.sendReply();
			this.instream = this.instream.slice(this.promptlength);
		}
	}
768397
def close_stream(self):
        
        if self.fout:
            fout = self.fout
            fout_fn = self.fout_fn
            self.fout.flush()
            self.fout.close()
            self.fout = None
            self.fout_fn = None
            return fout_fn
15491
def interact(self):
        

        sockets = [sys.stdin, self.channel]
        while True:
            ready = select.select(sockets, [], [])[0]

            if sys.stdin in ready:
                line = sys.stdin.readline().encode('latin1')
                if not line:
                    break
                self.write(line)

            if self.channel in ready:
                self.read(1, echo=True)
469056
def finish(self):
    
    if self.proc is None:
      return None
    self.proc.stdin.close()
    for thread in (self._out_thread, self._err_thread):
      thread.join()
    (out, err) = [
        b"".join(chunks) for chunks in (self._out_chunks, self._err_chunks)
    ]
    self.proc.stdout.close()
    self.proc.stderr.close()
    if self.proc.returncode:
      err = "\n".join([" ".join(self.cmd), err.decode("utf8")])
      raise IOError(err)
    del self.proc
    self.proc = None
    return out
1092366
def ensure_echo_on():
    """"""
    # tcgetattr will fail if stdin isn't a tty
    if not sys.stdin.isatty():
        return
    try:
        import termios
    except ImportError:
        return
    attributes = termios.tcgetattr(sys.stdin)
    if not attributes[3] & termios.ECHO:
        attributes[3] |= termios.ECHO
        termios.tcsetattr(sys.stdin, termios.TCSANOW, attributes)
298772
function emitLine() {	
			if(lineQueue.size() > 0)
			{				
				pause();

				sink({line: lineQueue.deq(), resume});
			}
			else if(streamEnd) {
				sink(new Bacon.End());
			}
			else {
				//If we've run out of lines to emit
				readStream.resume();
			}
		}
111113
def popenCatch(command, stdinString=None):
    
    logger.debug("Running the command: %s" % command)
    if stdinString != None:
        process = subprocess.Popen(command, shell=True,
                                   stdin=subprocess.PIPE, stdout=subprocess.PIPE, bufsize=-1)
        output, nothing = process.communicate(stdinString)
    else:
        process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=sys.stderr, bufsize=-1)
        output, nothing = process.communicate() #process.stdout.read().strip()
    sts = process.wait()
    if sts != 0:
        raise RuntimeError("Command: %s with stdin string '%s' exited with non-zero status %i" % (command, stdinString, sts))
    return output
20549
def _run(self, stdout=subprocess.PIPE):
        '''
        
        '''
        assert self._pop is None
        if self._input is not None:
            self._input._run()

        cwd = (self._cwd if self._cwd else os.getcwd()) + '/'

        def glob_or(expr):
            res = [expr]
            if self._expand and ('*' in expr or '?' in expr):
                if expr and expr[0] != '/':
                    expr = cwd + expr
                res = glob.glob(expr)
                if not res:
                    res = [expr]
            return res

        args = [glob_or(arg) for arg in self._args]
        stderr = subprocess.STDOUT if self._err_to_out else None
        assert not self._stdin or self._input is None, "*** ERROR: Stdin must be none outside of head of chain."
        stdin = self._stdin if self._input is None else self._input._pop.stdout
        if stdin is not None and getattr(stdin, 'fileno', None) is None:
            stdin = subprocess.PIPE
        cmd = [self._cmd] + list(itertools.chain.from_iterable(args))
        if self.debug:
            print "*** DEBUG: Run", cmd
        try:
            self._pop = subprocess.Popen(cmd, stdin=stdin, stdout=stdout, stderr=stderr,
                                         close_fds=True, cwd=self._cwd, env=self._env)
            if stdin == subprocess.PIPE:
                try:
                    # TODO: Write a non-blocking reader-writer to ship data here
                    self._pop.stdin.write(self._stdin.read())
                except AttributeError:
                    self._pop.stdin.write(self._stdin)
        except OSError:
            print "*** ERROR: %r failed at %r" % (self, self._original_cmd)
            raise
1054812
def streamer(main_method):
    """"""
    def main(arguments):
        streams = [StringIO(get_clipboard_data())] if (arguments and '-c' in arguments) else []
        streams = streams or ([file(_, 'r') for _ in arguments if os.path.isfile(argument)] if arguments else [])
        streams = streams or ([sys.stdin] if not (streams or arguments) else [])
        return main_method(arguments, streams)
    return main
63580
def eval_stdin():
    ''
    cmd = ['plash', 'eval']
    p = subprocess.Popen(cmd, stdin=sys.stdin, stdout=sys.stdout)
    exit = p.wait()
    if exit:
        raise subprocess.CalledProcessError(exit, cmd)