sys.stdin.read

Here are the examples of the python api sys.stdin.read taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

200 Examples 7

Example 1

Project: pyjs
Source File: cgihandler.py
View license
    def handle(self):
        try:
            contLen=int(os.environ['CONTENT_LENGTH'])
            data = sys.stdin.read(contLen)
        except:
            data = ""
        #execute the request
        self.handlePartialData(data)
        self.sendReply()
        self.close()

Example 2

Project: autotest
Source File: drone_utility.py
View license
def parse_input():
    input_chunks = []
    chunk_of_input = sys.stdin.read()
    while chunk_of_input:
        input_chunks.append(chunk_of_input)
        chunk_of_input = sys.stdin.read()
    pickled_input = ''.join(input_chunks)

    try:
        return pickle.loads(pickled_input)
    except Exception:
        separator = '*' * 50
        raise ValueError('Unpickling input failed\n'
                         'Input: %r\n'
                         'Exception from pickle:\n'
                         '%s\n%s\n%s' %
                         (pickled_input, separator, traceback.format_exc(),
                          separator))

Example 3

Project: WAPT
Source File: _diffcommand.py
View license
def read_file(filename):
    if filename == '-':
        c = sys.stdin.read()
    elif not os.path.exists(filename):
        raise OSError(
            "Input file %s does not exist" % filename)
    else:
        f = open(filename, 'rb')
        c = f.read()
        f.close()
    return c

Example 4

Project: ficloud
Source File: host.py
View license
    def git_post_receive(self, **kwargs):
        """
        Command is used inside git's post-receive hook
        """
        #!/home/alex/dev/ficloud/.env/bin/python

        p = re.compile(r'refs/heads/([^\s]+)')

        data = sys.stdin.read()
        print('>>%s<<' % data)
        m = p.search(data)
        if m:
            branch = m.group(1)
            app_name = os.path.basename(os.getcwd())
            print('\n\nDeploying app %s version %s ..\n\n' % (app_name, branch))

            self.deploy_app(app_name, branch)
        else:
            print('\n\nNB! No branch to deploy!\n\n')

Example 5

Project: playerpiano
Source File: piano.py
View license
def eat_key():
    """consume a key.  Exit on ^C"""
    c = sys.stdin.read(1)
    if c == '\x03': # ^C
        sys.exit(1)
    else:
        return c

Example 6

Project: cdent-py
Source File: __init__.py
View license
    def open(self, input):
        if isinstance(input, str):
            if input == '-':
                self.stream = sys.stdin.read()
            else:
                self.stream = input
        elif isinstance(input, file):
            self.stream = input.read()
        else:
            raise Exception("input to open is invalid")

Example 7

Project: pymo
Source File: refactor.py
View license
    def refactor_stdin(self, doctests_only=False):
        input = sys.stdin.read()
        if doctests_only:
            self.log_debug("Refactoring doctests in stdin")
            output = self.refactor_docstring(input, "<stdin>")
            if output != input:
                self.processed_file(output, "<stdin>", input)
            else:
                self.log_debug("No doctest changes in stdin")
        else:
            tree = self.refactor_string(input, "<stdin>")
            if tree and tree.was_changed:
                self.processed_file(unicode(tree), "<stdin>", input)
            else:
                self.log_debug("No changes in stdin")

Example 8

Project: termite-data-server
Source File: cssmin.py
View license
def main():
    import optparse
    import sys

    p = optparse.OptionParser(
        prog="cssmin", version=__version__,
        usage="%prog [--wrap N]",
        description="""Reads raw CSS from stdin, and writes compressed CSS to stdout.""")

    p.add_option(
        '-w', '--wrap', type='int', default=None, metavar='N',
        help="Wrap output to approximately N chars per line.")

    options, args = p.parse_args()
    sys.stdout.write(cssmin(sys.stdin.read(), wrap=options.wrap))

Example 9

Project: python-compat-runtime
Source File: runtime.py
View license
def main():
  config = runtime_config_pb2.Config()
  config.ParseFromString(base64.b64decode(sys.stdin.read()))
  server = wsgi_server.WsgiServer(
      ('localhost', 0),
      request_rewriter.runtime_rewriter_middleware(PHPRuntime(config)))
  server.start()
  print server.port
  sys.stdout.close()
  sys.stdout = sys.stderr
  try:
    while True:
      time.sleep(1)
  except KeyboardInterrupt:
    pass
  finally:
    server.quit()

Example 10

Project: cstar_perf
Source File: render.py
View license
def cli(opts, args):
    if args[1] == '-':
        data = sys.stdin.read()
    else:
        data = open(os.path.join(os.getcwd(), os.path.expanduser(args[1]))).read()

    try:
        data = formats['json'][0](data)
    except formats['json'][1]:
        raise formats['json'][2](u'%s ...' % data[:60])
        sys.exit(1)

    env = Environment(loader=FileSystemLoader(os.getcwd()))
    sys.stdout.write(env.get_template(args[0]).render(data))
    sys.exit(0)

Example 11

Project: postgresql-perf-tools
Source File: pg-top.py
View license
	def getkey(self):
		try:
			# return chr(self.scr.getch()) - thread unsafe
			key = sys.stdin.read(1)
		except KeyboardInterrupt:
			raise
		except:
			return chr(0)

		self.handle_key(key)
		return key

Example 12

Project: thundergate
Source File: linux_fun.py
View license
def wait_for_keypress(driver):
    if not driver.running:
        return
    orig_term = termios.tcgetattr(driver.kbd_h)
    new_term = orig_term[:]
    new_term[3] &= ~(termios.ICANON | termios.ECHO)
    termios.tcsetattr(driver.kbd_h, termios.TCSANOW, new_term)
    try:
        return sys.stdin.read(1)
    finally:
        termios.tcsetattr(driver.kbd_h, termios.TCSANOW, orig_term)

Example 13

Project: homebrew-pypi-poet
Source File: lint.py
View license
def main():
    parser = argparse.ArgumentParser(
        description="Alphabetize and tidy Homebrew resource stanzas.")
    parser.add_argument("-V", "--version", action="version",
                        version='homebrew-pypi-poet {}'.format(__version__))
    parser.add_argument("file", help="File containing resource stanzas, "
                        "or - for standard input.")
    args = parser.parse_args()
    if args.file == "-":
        buf = sys.stdin.read()
    else:
        with open(args.file, "r") as f:
            buf = f.read()
    print(lint(buf))

Example 14

Project: x-drone
Source File: refactor.py
View license
    def refactor_stdin(self, doctests_only=False):
        input = sys.stdin.read()
        if doctests_only:
            self.log_debug("Refactoring doctests in stdin")
            output = self.refactor_docstring(input, "<stdin>")
            if output != input:
                self.processed_file(output, "<stdin>", input)
            else:
                self.log_debug("No doctest changes in stdin")
        else:
            tree = self.refactor_string(input, "<stdin>")
            if tree and tree.was_changed:
                self.processed_file(unicode(tree), "<stdin>", input)
            else:
                self.log_debug("No changes in stdin")

Example 15

Project: babble
Source File: SimpleXMLRPCServer.py
View license
    def handle_request(self, request_text = None):
        """Handle a single XML-RPC request passed through a CGI post method.

        If no XML data is given then it is read from stdin. The resulting
        XML-RPC response is printed to stdout along with the correct HTTP
        headers.
        """

        if request_text is None and \
            os.environ.get('REQUEST_METHOD', None) == 'GET':
            self.handle_get()
        else:
            # POST data is normally available through stdin
            if request_text is None:
                request_text = sys.stdin.read()

            self.handle_xmlrpc(request_text)

Example 16

Project: astack
Source File: astack.py
View license
def get_stack_trace_from_file(filename):
    if filename.strip() == '-':
        return sys.stdin.read()
    elif filename.startswith('http:'):
        return urllib.urlopen(filename).read()
    else:
        with open(filename) as f:
            return f.read()

Example 17

Project: oleviewdotnet
Source File: refactor.py
View license
    def refactor_stdin(self, doctests_only=False):
        input = sys.stdin.read()
        if doctests_only:
            self.log_debug("Refactoring doctests in stdin")
            output = self.refactor_docstring(input, "<stdin>")
            if output != input:
                self.processed_file(output, "<stdin>", input)
            else:
                self.log_debug("No doctest changes in stdin")
        else:
            tree = self.refactor_string(input, "<stdin>")
            if tree and tree.was_changed:
                self.processed_file(unicode(tree), "<stdin>", input)
            else:
                self.log_debug("No changes in stdin")

Example 18

Project: datafari
Source File: refactor.py
View license
    def refactor_stdin(self, doctests_only=False):
        input = sys.stdin.read()
        if doctests_only:
            self.log_debug("Refactoring doctests in stdin")
            output = self.refactor_docstring(input, "<stdin>")
            if self.write_unchanged_files or output != input:
                self.processed_file(output, "<stdin>", input)
            else:
                self.log_debug("No doctest changes in stdin")
        else:
            tree = self.refactor_string(input, "<stdin>")
            if self.write_unchanged_files or (tree and tree.was_changed):
                self.processed_file(unicode(tree), "<stdin>", input)
            else:
                self.log_debug("No changes in stdin")

Example 19

Project: watchdog
Source File: n3p.py
View license
   def __init__(self, uri, branches, regexps):
      if uri == 'nowhere': pass
      elif (uri != 'file:///dev/stdin'):
         u = urllib.urlopen(uri)
         self.data = u.read()
         u.close()
      else: self.data = sys.stdin.read()
      self.pos = 0
      self.branches = branches
      self.regexps = regexps
      self.keywordMode = False
      self.keywords = set(("a", "is", "of", "this", "has"))
      self.productions = []
      self.memo = {}

Example 20

Project: bacpypes
Source File: extended_tag_list.py
View license
@bacpypes_debugging
def main():
    if _debug: main._debug("main")

    # parse the command line arguments
    args = ArgumentParser(description=__doc__).parse_args()
    if _debug: main._debug("    - args: %r", args)

    # suck in the test content
    text = sys.stdin.read()

    # parse it
    tag_list = ExtendedTagList(text)

    # dump it back out
    for tag in tag_list:
        tag.debug_contents()

Example 21

Project: canape
Source File: refactor.py
View license
    def refactor_stdin(self, doctests_only=False):
        input = sys.stdin.read()
        if doctests_only:
            self.log_debug("Refactoring doctests in stdin")
            output = self.refactor_docstring(input, "<stdin>")
            if output != input:
                self.processed_file(output, "<stdin>", input)
            else:
                self.log_debug("No doctest changes in stdin")
        else:
            tree = self.refactor_string(input, "<stdin>")
            if tree and tree.was_changed:
                self.processed_file(unicode(tree), "<stdin>", input)
            else:
                self.log_debug("No changes in stdin")

Example 22

Project: arduino-mqtt
Source File: bridge.py
View license
    def read_until(self, end):
        s = b""
        c = sys.stdin.read(1)
        while c not in end:
            s += c
            c = sys.stdin.read(1)
        return s

Example 23

Project: flake8
Source File: utils.py
View license
def stdin_get_value():
    # type: () -> str
    """Get and cache it so plugins can use it."""
    cached_value = getattr(stdin_get_value, 'cached_stdin', None)
    if cached_value is None:
        stdin_value = sys.stdin.read()
        if sys.version_info < (3, 0):
            cached_type = io.BytesIO
        else:
            cached_type = io.StringIO
        stdin_get_value.cached_stdin = cached_type(stdin_value)
        cached_value = stdin_get_value.cached_stdin
    return cached_value.getvalue()

Example 24

Project: llvm-p86
Source File: pre.py
View license
def _get_character_stream(filename):
    if filename == '-':
        chars = sys.stdin.read()
    else:
        fd = open(filename, "rb")
        chars = fd.read()
        fd.close()

    # python 3
    if not isinstance(chars, str):
        chars = chars.decode()

    return chars

Example 25

Project: clustershell
Source File: Clush.py
View license
def _stdin_thread_start(stdin_port, display):
    """Standard input reader thread entry point."""
    try:
        # Note: read length should be as large as possible for performance
        # yet not too large to not introduce artificial latency.
        # 64k seems to be perfect with an openssh backend (they issue 64k
        # reads) ; could consider making it an option for e.g. gsissh.
        bufsize = 64 * 1024
        # thread loop: blocking read stdin + send messages to specified
        #              port object
        buf = sys.stdin.read(bufsize)
        while buf:
            # send message to specified port object (with ack)
            stdin_port.msg(buf)
            buf = sys.stdin.read(bufsize)
    except IOError, ex:
        display.vprint(VERB_VERB, "stdin: %s" % ex)
    # send a None message to indicate EOF
    stdin_port.msg(None)

Example 26

Project: ocr_mnist
Source File: mlp.py
View license
    def testnet(self, inputs, targets):
        ''' for already trained network. test on another test set'''

        print shape(inputs), shape(self.weights1)
        self.nin = shape(inputs)[1]
        self.nout = shape(targets)[1]
        self.ndata = shape(inputs)[0]
        sys.stdin.read(1)
        inputs = concatenate((inputs,-ones((shape(inputs)[0],1))),axis=1)        
        out = self.mlpfwd(inputs)
        test_error = 0.5*sum((targets-out)**2)
        return test_error, out       

Example 27

Project: HTPC-Manager
Source File: command.py
View license
    def command(self):
        args = self.args
        if self.options.use_stdin:
            if self.options.verbose:
                print "Reading additional SQL from stdin (Ctrl-D or Ctrl-Z to finish)..."
            args.append(sys.stdin.read())
        self.conn = self.connection().getConnection()
        self.cursor = self.conn.cursor()
        for sql in args:
            self.execute_sql(sql)

Example 28

Project: alfredToday
Source File: _diffcommand.py
View license
def read_file(filename):
    if filename == '-':
        c = sys.stdin.read()
    elif not os.path.exists(filename):
        raise OSError(
            "Input file %s does not exist" % filename)
    else:
        f = open(filename, 'rb')
        c = f.read()
        f.close()
    return c

Example 29

Project: FanFicFare
Source File: utils.py
View license
def wrap_read():  # pragma: no cover
    """
    :rtype: str
    """
    try:
        return sys.stdin.read()
    except AttributeError:
        return sys.stdin.buffer.read()

Example 30

Project: cadquery-freecad-module
Source File: api.py
View license
def main(prog=None):
    """Entry point for the script "pyflakes"."""
    import optparse

    # Handle "Keyboard Interrupt" and "Broken pipe" gracefully
    _exitOnSignal('SIGINT', '... stopped')
    _exitOnSignal('SIGPIPE', 1)

    parser = optparse.OptionParser(prog=prog, version=__version__)
    (__, args) = parser.parse_args()
    reporter = modReporter._makeDefaultReporter()
    if args:
        warnings = checkRecursive(args, reporter)
    else:
        warnings = check(sys.stdin.read(), '<stdin>', reporter)
    raise SystemExit(warnings > 0)

Example 31

Project: synnefo
Source File: _common.py
View license
def read_from_file(f_name):
    if f_name == '-':
        return sys.stdin.read()
    else:
        try:
            with open(f_name) as file_desc:
                return file_desc.read()
        except IOError as e:
            raise CommandError(e)

Example 32

Project: pyhackedit
Source File: api.py
View license
def main(prog=None):
    """Entry point for the script "pyflakes"."""
    import optparse

    # Handle "Keyboard Interrupt" and "Broken pipe" gracefully
    _exitOnSignal('SIGINT', '... stopped')
    _exitOnSignal('SIGPIPE', 1)

    parser = optparse.OptionParser(prog=prog, version=__version__)
    (__, args) = parser.parse_args()
    reporter = modReporter._makeDefaultReporter()
    if args:
        warnings = checkRecursive(args, reporter)
    else:
        warnings = check(sys.stdin.read(), '<stdin>', reporter)
    raise SystemExit(warnings > 0)

Example 33

Project: conary
Source File: keymgmt.py
View license
def addKey(cfg, server, user):
    client = conaryclient.ConaryClient(cfg)
    repos = client.getRepos()

    if server is None:
        server = cfg.buildLabel.getHost()

    if user is None:
        user = cfg.user.find(server)[0]

    asciiKey = sys.stdin.read()
    binaryKey = openpgpfile.parseAsciiArmorKey(asciiKey)

    repos.addNewPGPKey(server, user, binaryKey)

Example 34

Project: SublimePythonIDE
Source File: api.py
View license
def main(prog=None):
    """Entry point for the script "pyflakes"."""
    import optparse

    # Handle "Keyboard Interrupt" and "Broken pipe" gracefully
    _exitOnSignal('SIGINT', '... stopped')
    _exitOnSignal('SIGPIPE', 1)

    parser = optparse.OptionParser(prog=prog, version=__version__)
    (__, args) = parser.parse_args()
    reporter = modReporter._makeDefaultReporter()
    if args:
        warnings = checkRecursive(args, reporter)
    else:
        warnings = check(sys.stdin.read(), '<stdin>', reporter)
    raise SystemExit(warnings > 0)

Example 35

Project: TrustRouter
Source File: refactor.py
View license
    def refactor_stdin(self, doctests_only=False):
        input = sys.stdin.read()
        if doctests_only:
            self.log_debug("Refactoring doctests in stdin")
            output = self.refactor_docstring(input, "<stdin>")
            if output != input:
                self.processed_file(output, "<stdin>", input)
            else:
                self.log_debug("No doctest changes in stdin")
        else:
            tree = self.refactor_string(input, "<stdin>")
            if tree and tree.was_changed:
                self.processed_file(str(tree), "<stdin>", input)
            else:
                self.log_debug("No changes in stdin")

Example 36

Project: pygtrie
Source File: example.py
View license
    def getch():
        """Reads single character from standard input."""
        attr = termios.tcgetattr(0)
        try:
            tty.setraw(0)
            return sys.stdin.read(1)
        finally:
            termios.tcsetattr(0, termios.TCSADRAIN, attr)

Example 37

Project: PyDev.Debugger
Source File: refactor.py
View license
    def refactor_stdin(self, doctests_only=False):
        input = sys.stdin.read()
        if doctests_only:
            self.log_debug("Refactoring doctests in stdin")
            output = self.refactor_docstring(input, "<stdin>")
            if self.write_unchanged_files or output != input:
                self.processed_file(output, "<stdin>", input)
            else:
                self.log_debug("No doctest changes in stdin")
        else:
            tree = self.refactor_string(input, "<stdin>")
            if self.write_unchanged_files or (tree and tree.was_changed):
                self.processed_file(unicode(tree), "<stdin>", input)
            else:
                self.log_debug("No changes in stdin")

Example 38

Project: simian
Source File: runtime.py
View license
def main():
  config = runtime_config_pb2.Config()
  config.ParseFromString(base64.b64decode(sys.stdin.read()))
  server = wsgi_server.WsgiServer(
      ('localhost', 0),
      request_rewriter.runtime_rewriter_middleware(PHPRuntime(config)))
  server.start()
  print server.port
  sys.stdout.close()
  sys.stdout = sys.stderr
  try:
    while True:
      time.sleep(1)
  except KeyboardInterrupt:
    pass
  finally:
    server.quit()

Example 39

Project: InspectorD
Source File: ejabberd_auth.py
View license
def ejabberd_in():
    logging.debug("trying to read 2 bytes from ejabberd:")
    try:
      input_length = sys.stdin.read(2)
    except IOError:
      logging.debug("ioerror")
    if len(input_length) is not 2:
      logging.debug("ejabberd sent us wrong things!")
      raise EjabberdInputError('Wrong input from ejabberd!')
    logging.debug('got 2 bytes via stdin: %s'%input_length)
    (size,) = unpack('>h', input_length)
    logging.debug('size of data: %i'%size)
    income=sys.stdin.read(size).split(':')
    logging.debug("incoming data: %s"%income)
    return income

Example 40

Project: errbot
Source File: cli.py
View license
def _read_dict():
    import collections
    new_dict = eval(sys.stdin.read())
    if not isinstance(new_dict, collections.Mapping):
        raise ValueError("A dictionary written in python is needed from stdin. Type=%s, Value = %s" % (type(new_dict),
                                                                                                       repr(new_dict)))
    return new_dict

Example 41

Project: pyjvm
Source File: vmo.py
View license
def vmo4_read___I(frame, args):
    '''Read single byte'''
    c = sys.stdin.read(1)
    if c == '':
        frame.stack.append(-1)
    else:
        frame.stack.append(ord(c))

Example 42

Project: pol
Source File: terminal.py
View license
def wait_for_keypress():
    """ Waits for a single keypress """
    with raw_mode():
        purge_stdin()
        try:
            PyOS_InputHook() # allows GTK to manage clipboard
            ret = sys.stdin.read(1)
        except KeyboardInterrupt:
            ret = 0
    return ret

Example 43

Project: wikiclass
Source File: score.py
View license
def main(argv=None):
    args = docopt.docopt(__doc__, argv=argv)

    scorer_model = MLScorerModel.load(open(args['<model-file>'], 'rb'))
    if args['<text>'] == "<stdin>":
        text = sys.stdin.read()
    else:
        text = open(args['<text>']).read()

    print(score(scorer_model, text))

Example 44

Project: dogapi
Source File: dashboard.py
View license
    def _update(self, args):
        self.dog.timeout = args.timeout
        format = args.format
        graphs = args.graphs
        if args.graphs is None:
            graphs = sys.stdin.read()
        try:
            graphs = json.loads(graphs)
        except:
            raise Exception('bad json parameter')

        res = self.dog.update_dashboard(args.dashboard_id, args.title, args.description,
                                        graphs, template_variables=args.template_variables)
        report_warnings(res)
        report_errors(res)
        if format == 'pretty':
            print(self._pretty_json(res))
        else:
            print(json.dumps(res))

Example 45

Project: kbengine
Source File: refactor.py
View license
    def refactor_stdin(self, doctests_only=False):
        input = sys.stdin.read()
        if doctests_only:
            self.log_debug("Refactoring doctests in stdin")
            output = self.refactor_docstring(input, "<stdin>")
            if self.write_unchanged_files or output != input:
                self.processed_file(output, "<stdin>", input)
            else:
                self.log_debug("No doctest changes in stdin")
        else:
            tree = self.refactor_string(input, "<stdin>")
            if self.write_unchanged_files or (tree and tree.was_changed):
                self.processed_file(str(tree), "<stdin>", input)
            else:
                self.log_debug("No changes in stdin")

Example 46

Project: pyxc-pj
Source File: main.py
View license
def codeToCode():
    py = sys.stdin.read()
    try:
        js = pj.api_internal.codeToCode(py)
        sys.stdout.write(js)
    except Exception as e:
        writeExceptionJsonAndDie(e)

Example 47

Project: wikt2dict
Source File: wiki.py
View license
  def process(self):
    while True:
      buf = sys.stdin.read(self.buffer_size)
      if buf == "":
        break

      self.xml_parser.Parse(buf)

Example 48

Project: sensu-py
Source File: utils.py
View license
def read_event(data=None):
    event = {}
    # get from stdin if not specified
    if not data:
        # check for env var (testing)
        if os.environ.has_key('SENSU_EVENT'):
            event = json.loads(os.environ.get('SENSU_EVENT'))
        else:
            event = json.loads(sys.stdin.read())
    else:
        event = json.loads(data)
    return event

Example 49

Project: clevercss
Source File: ccss.py
View license
def convert_stream():
    import sys
    try:
        print(clevercss.convert(sys.stdin.read()))
    except (ParserError, EvalException) as e:
        sys.stderr.write('Error: %s\n' % e)
        sys.exit(1)

Example 50

Project: pyflakes
Source File: api.py
View license
def main(prog=None, args=None):
    """Entry point for the script "pyflakes"."""
    import optparse

    # Handle "Keyboard Interrupt" and "Broken pipe" gracefully
    _exitOnSignal('SIGINT', '... stopped')
    _exitOnSignal('SIGPIPE', 1)

    parser = optparse.OptionParser(prog=prog, version=__version__)
    (__, args) = parser.parse_args(args=args)
    reporter = modReporter._makeDefaultReporter()
    if args:
        warnings = checkRecursive(args, reporter)
    else:
        warnings = check(sys.stdin.read(), '<stdin>', reporter)
    raise SystemExit(warnings > 0)