Open a file for reading or return ``stdin``.

    Adapted from StackOverflow user "Wolph"
    (http://stackoverflow.com/a/17603000).
551263
def smart_open_read(path=None, mode='rb', encoding=None, try_gzip=False):
    
    assert mode in ('r', 'rb')
    assert path is None or isinstance(path, (str, _oldstr))
    assert isinstance(mode, (str, _oldstr))
    assert encoding is None or isinstance(encoding, (str, _oldstr))
    assert isinstance(try_gzip, bool)

    fh = None
    binfh = None
    gzfh = None
    if path is None:
        # open stdin
        fh = io.open(sys.stdin.fileno(), mode=mode, encoding=encoding)

    else:
        # open an actual file

        if try_gzip:
            # gzip.open defaults to mode 'rb'
            gzfh = try_open_gzip(path)

        if gzfh is not None:
            logger.debug('Opening gzip''ed file.')
            # wrap gzip stream
            binfh = io.BufferedReader(gzfh)
            if 'b' not in mode:
                # add a text wrapper on top
                logger.debug('Adding text wrapper.')
                fh = io.TextIOWrapper(binfh, encoding=encoding)

        else:
            fh = io.open(path, mode=mode, encoding=encoding)

    yield_fh = fh
    if fh is None:
        yield_fh = binfh

    try:
        yield yield_fh

    finally:
        # close all open files
        if fh is not None:
            # make sure we don't close stdin
            if fh.fileno() != sys.stdin.fileno():
                fh.close()

        if binfh is not None:
            binfh.close()

        if gzfh is not None:
            gzfh.close()
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
525071
private Input processRegularFileInput(String input) throws IOException {
    File inputFile = new File(input);
    if (!inputFile.exists()) {
      throw new IOException("Input does not exist: " + input);
    }
    if (pipeFiles) {
      SamReader samReader = SamReaderFactory.makeDefault().open(inputFile);
      return new Input(input, STDIN_FILE_NAME, 
          new SamReaderToSAMFilePump(samReader)); 
    } else {
      return new Input(input, input, null);
    }
  }
272703
def standard_input():
    """"""
    with click.get_text_stream("stdin") as stdin:
        while stdin.readable():
            line = stdin.readline()
            if line:
                yield line.strip().encode("utf-8")
267269
def reader(fname):
    ''''''
    f = pyfastaq.utils.open_file_read(fname)

    for line in f:
        if line.startswith('[') or (not '\t' in line):
            continue

        yield alignment.Alignment(line)

    pyfastaq.utils.close(f)
1283408
def stdin_readable():
    """"""
    if not WINDOWS:
        try:
            return bool(select([sys.stdin], [], [], 0)[0])
        except Exception:
            logger.log_exc()
    try:
        return not sys.stdin.isatty()
    except Exception:
        logger.log_exc()
    return False
276968
def binary_value_or_stdin(value):
    
    if value is None:
        reader = io.open(sys.stdin.fileno(), mode='rb', closefd=False)
        return reader.read()
    elif six.PY3:
        return os.fsencode(value)
    else:
        return value
387741
def open_file(self, file_):
        
        with open(file_, 'r', encoding='utf-8') as file:
            text = ''
            for line in file:
                text += line
        return text
397181
def input(self, _in, out, **kw):
        
        # create a temp file
        tmp = NamedTemporaryFile(suffix='.js', delete=False)
        tmp.close()  # close it so windows can read it

        # write to a temp file
        elm_make = self.binary or 'elm-make'
        change_directory = bool(self.change_directory or False)
        source = kw['source_path']
        source_dir = os.path.dirname(source)
        exec_dir = source_dir if change_directory else os.getcwd()
        write_args = [elm_make, source, '--output', tmp.name, '--yes']
        with excursion(exec_dir), TemporaryFile(mode='w') as fake_write_obj:
            self.subprocess(write_args, fake_write_obj)

        # read the temp file
        cat_or_type = 'type' if platform == 'win32' else 'cat'
        read_args = [cat_or_type, tmp.name]
        self.subprocess(read_args, out)
        os.remove(tmp.name)
223164
def _process_stdin(self):
        
        with nonblocking(sys.stdin.fileno()):
            data = self._stdin_reader.read()

        # Send input in chunks of 4k.
        step = 4056
        for i in range(0, len(data), step):
            self._send_packet({
                'cmd': 'in',
                'data': data[i:i + step],
            })
694981
def _text_or_file(input_):
    '''
    
    '''
    if _isfile(input_):
        with salt.utils.files.fopen(input_) as fp_:
            out = salt.utils.stringutils.to_str(fp_.read())
    else:
        out = salt.utils.stringutils.to_str(input_)

    return out
1141313
function readStdin() {
    var stdin = process.stdin,
      fd = stdin.isTTY && process.platform !== 'win32' ?
        fs.openSync('/dev/tty', 'rs') : stdin.fd,
      bufSize = stdin.isTTY ? DEFAULT_BUF_SIZE :
        (fs.fstatSync(fd).size || DEFAULT_BUF_SIZE),
      buffer = Buffer.allocUnsafe && Buffer.alloc ? Buffer.alloc(bufSize) : new Buffer(bufSize),
      rsize, input = '';
    while (true) {
      rsize = 0;
      try {
        rsize = fs.readSync(fd, buffer, 0, bufSize);
      } catch (e) {
        if (e.code === 'EOF') { break; }
        throw e;
      }
      if (rsize === 0) { break; }
      input += buffer.toString(program.encoding, 0, rsize);
    }
    return input;
  }
324291
def open(self):
        """"""
        with open(self.filename, 'rb') as file_open:
            binary = file_open.read()

        try:
            return binary.decode()
        except UnicodeDecodeError:
            encoding = get_encoding(binary)
            try:
                return binary.decode(encoding)
            except LookupError:
                return binary.decode(errors='ignore')
            except:  # pylint: disable=W0702
                open_error(self.filename)
        except:  # pylint: disable=W0702
            open_error(self.filename)
90574
private function read_from_file_or_stdin( $arg ) {
		if ( '-' !== $arg ) {
			$readfile = $arg;
			if ( ! file_exists( $readfile ) || ! is_file( $readfile ) ) {
				WP_CLI::error( "Unable to read content from '{$readfile}'." );
			}
		} else {
			$readfile = 'php://stdin';
		}
		return file_get_contents( $readfile );
	}
953919
def main():
    
    filename = pmag.get_named_arg('-f')
    if not filename:
        return
    with open(filename, 'rb+') as f:
        content = f.read()
        f.seek(0)
        f.write(content.replace(b'\r', b''))
        f.truncate()
830377
def _open(self, file, mode_int, closefd):
        """"""
        if isinstance(file, (_unicode, bytes)):
            if _os.path.isfile(file):
                if 'x' in self.mode:
                    raise OSError("File exists: {0!r}".format(self.name))
                elif set(self.mode).issuperset('w+'):
                    # truncate the file, because SFM_RDWR doesn't:
                    _os.close(_os.open(file, _os.O_WRONLY | _os.O_TRUNC))
            openfunction = _snd.sf_open
            if isinstance(file, _unicode):
                if _sys.platform == 'win32':
                    openfunction = _snd.sf_wchar_open
                else:
                    file = file.encode(_sys.getfilesystemencoding())
            file_ptr = openfunction(file, mode_int, self._info)
        elif isinstance(file, int):
            file_ptr = _snd.sf_open_fd(file, mode_int, self._info, closefd)
        elif _has_virtual_io_attrs(file, mode_int):
            file_ptr = _snd.sf_open_virtual(self._init_virtual_io(file),
                                            mode_int, self._info, _ffi.NULL)
        else:
            raise TypeError("Invalid file: {0!r}".format(self.name))
        _error_check(_snd.sf_error(file_ptr),
                     "Error opening {0!r}: ".format(self.name))
        if mode_int == _snd.SFM_WRITE:
            # Due to a bug in libsndfile version <= 1.0.25, frames != 0
            # when opening a named pipe in SFM_WRITE mode.
            # See http://github.com/erikd/libsndfile/issues/77.
            self._info.frames = 0
            # This is not necessary for "normal" files (because
            # frames == 0 in this case), but it doesn't hurt, either.
        return file_ptr
708287
def open(self, input_streams=['stdin'], output_streams=['stderr', 'stdout']):
        
        shell = dict()
        shell['rsp:InputStreams'] = " ".join(input_streams)
        shell['rsp:OutputStreams'] = " ".join(output_streams)
        shell['rsp:IdleTimeout'] = str(self.idle_timeout)

        if self.working_directory is not None:
            shell['rsp:WorkingDirectory'] = str(self.working_directory)

        if self.environment is not None:
            variables = []
            for key, value in self.environment.items():
                variables.append({'#text': str(value), '@Name': key})
            shell['rsp:Environment'] = {'Variable': variables}

        response = self.session.create(self.resource, {'rsp:Shell': shell})
        self.__shell_id = response['rsp:Shell']['rsp:ShellId']