sys.stdin.readline

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

200 Examples 7

Example 1

Project: the-coding-interview
Source File: lawnmower2.py
View license
def get_data():
    numcases = int(sys.stdin.readline())
    for case in range(1,numcases+1):
        N, M = [int(v) for v in sys.stdin.readline().strip().split()]
        data = []
        for line_number in range(N):
            line = sys.stdin.readline().strip().split()
            data.append(line)
        yield (case, data)

Example 2

Project: the-coding-interview
Source File: treasure.py
View license
def get_data():
  numcases = int(sys.stdin.readline())
  for case in range(1,numcases+1):
      num_keys, num_chests = map(int, sys.stdin.readline().split())
      keyring = list(map(int, sys.stdin.readline().split()))
      # Store chests in dictionary
      chests = defaultdict(list)
      for id in range(1,num_chests+1):
        chest_data = list(map(int, sys.stdin.readline().split()))
        unlock_key, content = chest_data[0], chest_data[2:]
        chest = Chest(id, content)
        chests[unlock_key].append(chest)
      yield (case, keyring, chests)

Example 3

Project: the-coding-interview
Source File: lawnmower.py
View license
def get_data():
    numcases = int(sys.stdin.readline())
    for case in range(1,numcases+1):
        N, M = [int(v) for v in sys.stdin.readline().strip().split()]
        data = []
        for line_number in range(N):
            line = sys.stdin.readline().strip().split()
            data.append([int(i) for i in line])
        yield (case, data)

Example 4

Project: the-coding-interview
Source File: lawnmower2.py
View license
def get_data():
    numcases = int(sys.stdin.readline())
    for case in range(1,numcases+1):
        N, M = [int(v) for v in sys.stdin.readline().strip().split()]
        data = []
        for line_number in range(N):
            line = sys.stdin.readline().strip().split()
            data.append(line)
        yield (case, data)

Example 5

Project: the-coding-interview
Source File: treasure.py
View license
def get_data():
  numcases = int(sys.stdin.readline())
  for case in range(1,numcases+1):
      num_keys, num_chests = map(int, sys.stdin.readline().split())
      keyring = list(map(int, sys.stdin.readline().split()))
      # Store chests in dictionary
      chests = defaultdict(list)
      for id in range(1,num_chests+1):
        chest_data = list(map(int, sys.stdin.readline().split()))
        unlock_key, content = chest_data[0], chest_data[2:]
        chest = Chest(id, content)
        chests[unlock_key].append(chest)
      yield (case, keyring, chests)

Example 6

Project: the-coding-interview
Source File: lawnmower.py
View license
def get_data():
    numcases = int(sys.stdin.readline())
    for case in range(1,numcases+1):
        N, M = [int(v) for v in sys.stdin.readline().strip().split()]
        data = []
        for line_number in range(N):
            line = sys.stdin.readline().strip().split()
            data.append([int(i) for i in line])
        yield (case, data)

Example 7

Project: cgat
Source File: Rsdb2Plot.py
View license
    def WritePreamble( self ):
        """write preamble. Stop at '//', ignore '#' at first position."""
        
        while 1:
            line = sys.stdin.readline()
            
            if not line: break
            if line[0] == "#": continue
            if line[0:2] == "//": break

Example 8

Project: upsidedown
Source File: upsidedown.py
View license
def main():
    """Main method for running upsidedown.py from the command line."""
    import sys

    output = []
    line = sys.stdin.readline()

    while line:
        line = line.strip("\n")
        output.append(transform(line))

        line = sys.stdin.readline()
    output.reverse()
    print("\n".join(output))

Example 9

Project: imagrium
Source File: telnetlib.py
View license
    def mt_interact(self):
        """Multithreaded version of interact()."""
        import thread
        thread.start_new_thread(self.listener, ())
        while 1:
            line = sys.stdin.readline()
            if not line:
                break
            self.write(line)

Example 10

Project: typhon-vx
Source File: napalmex4.py
View license
def stat():
	cur.execute("select count(1) from keys where key like '%s' and status=1"%(emptykey))
	queue_dat=cur.fetchone()[0]
	tsql.execute("select count(1) from keystreams where jobnum = -1")
	queue_bursts=tsql.fetchone()[0]
	tsql.execute("select count(1) from keystreams where submitted != -1")
	jobs=tsql.fetchone()[0]
#	print("=== %s:%s ==="%(gsmkrakenhost,gsmkrakenport))
	print("C:%s F:%s P:%s R:%s DUP:%s; q:%s dats, %s ks; %s jobs; %i FPS; %.2f k/s"%(cracked,failed,plain,reused,dup_results,queue_dat,queue_bursts,jobs,(bursts_recv/(time.time()-start)*16320),(cracked/(time.time()-start))))
	try:
		line=sys.stdin.readline()
		print(line)
	except:
		pass

Example 11

View license
    def mt_interact(self):
        """Multithreaded version of interact()."""
        import thread
        thread.start_new_thread(self.listener, ())
        while 1:
            line = sys.stdin.readline()
            if not line:
                break
            self.write(line)

Example 12

Project: cgat
Source File: Rsdb2Plot.py
View license
    def WritePostamble( self ):
        """write postamble. Stop at '//', ignore '#' at first position."""
        while 1:
            line = sys.stdin.readline()
            
            if not line: break
            if line[0] == "#": continue
            if line[0:2] == "//": break
            
            print line

Example 13

Project: cgat
Source File: Rsdb2Html.py
View license
    def WritePreamble( self ):
        """write preamble. Stop at '//', ignore '#' at first position."""
        
        while 1:
            line = sys.stdin.readline()
            
            if not line: break
            if line[0] == "#": continue
            if line[0:2] == "//": break
            
            print line

Example 14

Project: orthrus
Source File: commands.py
View license
    def run(self):
        util.color_print(util.bcolors.BOLD + util.bcolors.HEADER, "[+] Destroy Orthrus workspace")
        util.color_print_singleline(util.bcolors.BOLD + util.bcolors.HEADER, "[?] Delete complete workspace? [y/n]...: ")

        if (self.testinput and 'y' in self.testinput) or 'y' in sys.stdin.readline()[0]:
            util.color_print_singleline(util.bcolors.OKGREEN, "\t\t[+] Deleting all files... ")
            if not os.path.exists(self._config['orthrus']['directory']):
                util.color_print(util.bcolors.OKBLUE, "destroyed already")
            else:
                shutil.rmtree(self._config['orthrus']['directory'])
                if not os.path.isdir(self._config['orthrus']['directory']):
                    util.color_print(util.bcolors.OKGREEN, "done")
                else:
                    util.color_print(util.bcolors.FAIL, "failed")
                    return False
        return True

Example 15

Project: bup
Source File: split-cmd.py
View license
    def read_ids():
        while 1:
            line = sys.stdin.readline()
            if not line:
                break
            if line:
                line = line.strip()
            try:
                it = cp.get(line.strip())
                next(it, None)  # skip the file type
            except KeyError as e:
                add_error('error: %s' % e)
                continue
            yield IterToFile(it)

Example 16

Project: robopoker
Source File: api.py
View license
def request():
    def rl():
        line = sys.stdin.readline()
        return line.strip()
    name = rl()
    cards = rl()
    rl()
    actions = []
    while True:
        act = rl()
        if not act: break
        actions.append(act)
    return name, cards, actions, sys.stdin

Example 17

Project: raspberry_pwn
Source File: GoodFETConsole.py
View license
    def run(self):
        self.prompt();
        #for cmd in sys.stdin:
        while 1:
            cmd=sys.stdin.readline();
            if not cmd: break;
            if(cmd.strip()!=""):
                self.handle(cmd);
            self.prompt();

Example 18

Project: PythonScript
Source File: telnetlib.py
View license
    def mt_interact(self):
        """Multithreaded version of interact()."""
        import thread
        thread.start_new_thread(self.listener, ())
        while 1:
            line = sys.stdin.readline()
            if not line:
                break
            self.write(line)

Example 19

Project: WAPT
Source File: telnetlib.py
View license
    def mt_interact(self):
        """Multithreaded version of interact()."""
        import thread
        thread.start_new_thread(self.listener, ())
        while 1:
            line = sys.stdin.readline()
            if not line:
                break
            self.write(line)

Example 20

Project: minos
Source File: loop_eventgen.py
View license
def main(max):
    start = time.time()
    report = open('/tmp/report', 'w')
    i = 0
    while 1:
        childutils.pcomm.stdout('the_data')
        data = sys.stdin.readline()
        report.write(str(i) + ' @ %s\n' % childutils.get_asctime())
        report.flush()
        i+=1
        if max and i >= max:
            end = time.time()
            report.write('%s per second\n' % (i / (end - start)))
            sys.exit(0)

Example 21

Project: QLDS-Manager
Source File: rcon.py
View license
    def __input(self):
        def wait_for_stdin(queue__):
            while True:
                input_ = sys.stdin.readline()
                if len(input_) > 1:
                    queue__.put(input_)

        queue_ = queue.Queue()

        thread = threading.Thread(target=wait_for_stdin, args=[queue_])
        thread.daemon = True
        thread.start()

        return queue_

Example 22

Project: gaffer
Source File: echo.py
View license
    def run(self):
        while self.alive:
            c = sys.stdin.readline()
            sys.stdout.write(c)
            sys.stdout.flush()
            time.sleep(0.1)

Example 23

Project: langchangetrack
Source File: findNearest.py
View license
def process(filename):
    m = gensim.models.Word2Vec.load_word2vec_format(filename)
    print "query (ctrl-c to quit): ",
    line = sys.stdin.readline()
    while line:
        word = line.rstrip()
        print word
        tuples  = m.most_similar(word, topn=10)
        for w, s in tuples:
            print w, s
        print "----------------------------------"
        print "query (ctrl-c to quit): ",
        line = sys.stdin.readline()

Example 24

Project: vivisect
Source File: envitools.py
View license
def lockStepEmulator(emu, trace):
    while True:
        print "Lockstep: 0x%.8x" % emu.getProgramCounter()
        try:
            pc = emu.getProgramCounter()
            op = emu.parseOpcode(pc)
            trace.stepi()
            emu.stepi()
            cmpRegs(emu, trace)
        except RegisterException, msg:
            print "Lockstep Error: %s: %s" % (repr(op),msg)
            setRegs(emu, trace)
            sys.stdin.readline()
        except Exception, msg:
            traceback.print_exc()
            print "Lockstep Error: %s" % msg
            return

Example 25

Project: oleviewdotnet
Source File: telnetlib.py
View license
    def mt_interact(self):
        """Multithreaded version of interact()."""
        import thread
        thread.start_new_thread(self.listener, ())
        while 1:
            line = sys.stdin.readline()
            if not line:
                break
            self.write(line)

Example 26

Project: scalyr-agent-2
Source File: tcollector.py
View license
    def read(self):
        """Read lines from STDIN and store them.  We allow this to
           be blocking because there should only ever be one
           StdinCollector and no normal collectors, so the ReaderThread
           is only serving us and we're allowed to block it."""

        global ALIVE
        line = sys.stdin.readline()
        if line:
            self.datalines.append(line.rstrip())
        else:
            ALIVE = False

Example 27

Project: smap
Source File: gwiki2rst.py
View license
def convert_code(line):
    if line.startswith('{{{'):
        print
        print ".. code-block:: python"
        print
        while True:
            line = sys.stdin.readline()
            if line.startswith('}}}'): return True
            else: print "  " + line.strip()
    return False

Example 28

Project: vivisect
Source File: main.py
View license
def safeReadline():
    while True:
        try: # Crazy loop for freebsd readline failure
            r = sys.stdin.readline()
            break
        except IOError,e:
            if e.errno == errno.EINTR:
                continue
            raise
    return r

Example 29

Project: bh2014
Source File: telnetlib.py
View license
    def mt_interact(self):
        """Multithreaded version of interact()."""
        import thread
        thread.start_new_thread(self.listener, ())
        while 1:
            line = sys.stdin.readline()
            if not line:
                break
            self.write(line)

Example 30

Project: pymo
Source File: telnetlib.py
View license
    def mt_interact(self):
        """Multithreaded version of interact()."""
        import thread
        thread.start_new_thread(self.listener, ())
        while 1:
            line = sys.stdin.readline()
            if not line:
                break
            self.write(line)

Example 31

Project: synaps
Source File: storm.py
View license
def readMsg():
    msg = ""
    while True:
        line = sys.stdin.readline()[0:-1]
        if line == "end":
            break
        msg = msg + line + "\n"
    return json_decode(msg[0:-1])

Example 32

Project: SublimeIBus
Source File: sublime-ibus-agent.py
View license
    def __stdin_cb(self, fd, condition):
        try:
            expr = sys.stdin.readline()
            exec(expr)
        except:
            import traceback
            print_command('error', 'error expr: ' + expr)
            print_command('error', traceback.format_exc())
        return True

Example 33

Project: vumi
Source File: parse_log_messages.py
View license
    def parse(self):
        while True:
            line = sys.stdin.readline()
            if not line:
                break
            self.readline(line)

Example 34

Project: PythonScript
Source File: telnetlib.py
View license
    def mt_interact(self):
        """Multithreaded version of interact()."""
        import thread
        thread.start_new_thread(self.listener, ())
        while 1:
            line = sys.stdin.readline()
            if not line:
                break
            self.write(line)

Example 35

Project: typhon-vx
Source File: napalmex.py
View license
def stat():
	cur.execute("select count(1) from keys where key like '%s' and status=1"%(emptykey))
	queue_dat=cur.fetchone()[0]
	tsql.execute("select count(1) from keystreams where jobnum = -1")
	queue_bursts=tsql.fetchone()[0]
	tsql.execute("select count(1) from keystreams where submitted != -1")
	jobs=tsql.fetchone()[0]
	print("C:%s F:%s P:%s R:%s DUP:%s; q:%s dats, %s ks; %s jobs; %i FPS; %.2f k/s"%(cracked,failed,plain,reused,dup_results,queue_dat,queue_bursts,jobs,(bursts_recv/(time.time()-start)*16320),(cracked/(time.time()-start))))
	try:
		line=sys.stdin.readline()
		print(line)
	except:
		pass

Example 36

Project: chipsec
Source File: telnetlib.py
View license
    def mt_interact(self):
        """Multithreaded version of interact()."""
        import thread
        thread.start_new_thread(self.listener, ())
        while 1:
            line = sys.stdin.readline()
            if not line:
                break
            self.write(line)

Example 37

Project: minos
Source File: sample_eventlistener.py
View license
def main():
    while 1:
        write_stdout('READY\n') # transition from ACKNOWLEDGED to READY
        line = sys.stdin.readline()  # read header line from stdin 
        write_stderr(line) # print it out to stderr (testing only)
        headers = dict([ x.split(':') for x in line.split() ])
        data = sys.stdin.read(int(headers['len'])) # read the event payload
        write_stderr(data) # print the event payload to stderr (testing only)
        write_stdout('RESULT 2\nOK') # transition from BUSY to ACKNOWLEDGED

Example 38

View license
def main():
    write_stdout('READY\n') # transition from ACKNOWLEDGED to READY
    line = sys.stdin.readline()  # read a line from stdin from supervisord
    write_stderr(line) # print it out to stderr (testing only)
    headers = dict([ x.split(':') for x in line.split() ])
    data = sys.stdin.read(int(headers['len'])) # read the event payload
    write_stderr(data) # print the event payload to stderr (testing only)
    write_stdout('RESULT 2\nOK') # transition from READY to ACKNOWLEDGED

Example 39

Project: buildtools-BaseTools
Source File: MkPkg.py
View license
def CheckForExistingDp(Path):
    if os.path.exists(Path):
        Logger.Info(ST.MSG_DISTRIBUTION_PACKAGE_FILE_EXISTS % Path)
        Input = stdin.readline()
        Input = Input.replace('\r', '').replace('\n', '')
        if Input.upper() != "Y":
            Logger.Error("\nMkPkg", ABORT_ERROR, ST.ERR_USER_ABORT, RaiseError=True)

Example 40

Project: python-pyhsm
Source File: keystore_unlock.py
View license
def get_otp(hsm, args):
    """ Get OTP from YubiKey. """
    if args.no_otp:
        return None
    if hsm.version.have_unlock():
        if args.stdin:
            otp = sys.stdin.readline()
            while otp and otp[-1] == '\n':
                otp = otp[:-1]
        else:
            otp = raw_input('Enter admin YubiKey OTP (press enter to skip) : ')
        if len(otp) == 44:
            # YubiHSM admin OTP's always have a public_id length of 6 bytes
            return otp
        if otp:
            sys.stderr.write("ERROR: Invalid YubiKey OTP\n")
    return None

Example 41

Project: babble
Source File: telnetlib.py
View license
    def mt_interact(self):
        """Multithreaded version of interact()."""
        import thread
        thread.start_new_thread(self.listener, ())
        while 1:
            line = sys.stdin.readline()
            if not line:
                break
            self.write(line)

Example 42

Project: zero
Source File: __init__.py
View license
    @staticmethod
    def iter_stdin():
        ''' Reads a line from stdin, stripping right side white space, unmarshalling
            json. Returns None when stdin is closed.
        '''
        from json import loads
        def liner():
            res = sys.stdin.readline()
            if not res:
                return None
            return loads(res.rstrip())
        return iter(liner, None)

Example 43

Project: gaffer
Source File: echo.py
View license
    def run(self):
        while self.alive:
            c = sys.stdin.readline()
            sys.stdout.write(c)
            sys.stdout.flush()
            time.sleep(0.1)

Example 44

Project: cmdbac
Source File: cluster.py
View license
def read_repo_data():
    repo_names = []
    all_data = []

    line = sys.stdin.readline()
    while line:
        repo_data = map(float, line.split()[1:])
        all_data.append(repo_data)
        repo_names.append(line.split()[0])

        assert(len(repo_data) + 1 == len(REPO_FEATURE_NAMES))

        line = sys.stdin.readline()
    
    return repo_names, all_data

Example 45

Project: TrustRouter
Source File: telnetlib.py
View license
    def mt_interact(self):
        """Multithreaded version of interact()."""
        import _thread
        _thread.start_new_thread(self.listener, ())
        while 1:
            line = sys.stdin.readline()
            if not line:
                break
            self.write(line.encode('ascii'))

Example 46

Project: vivisect
Source File: __init__.py
View license
def safeReadline():
    while True:
        try: # Crazy loop for freebsd readline failure
            r = sys.stdin.readline()
            break
        except IOError,e:
            if e.errno == errno.EINTR:
                continue
            raise
    return r

Example 47

Project: climber
Source File: telnetlib.py
View license
    def mt_interact(self):
        """Multithreaded version of interact()."""
        import thread
        thread.start_new_thread(self.listener, ())
        while 1:
            line = sys.stdin.readline()
            if not line:
                break
            self.write(line)

Example 48

Project: PokemonGo-Bot-Desktop
Source File: telnetlib.py
View license
    def mt_interact(self):
        """Multithreaded version of interact()."""
        import thread
        thread.start_new_thread(self.listener, ())
        while 1:
            line = sys.stdin.readline()
            if not line:
                break
            self.write(line)

Example 49

Project: sftmumblebot
Source File: ConsoleConnection.py
View license
    def _listen(self):
        """
        read data from stdin, and interpret it as a chat message
        """
        try:
            line = sys.stdin.readline()
        except KeyboardInterrupt:
            self._log("keyboard interrupt", 1)
            self._invokeTextCallback("console", "Goodbye.")
            return False

        line = util.try_decode(line, self._encoding)
        self._invokeTextCallback("console", line)
        return True

Example 50

Project: pydle
Source File: irccat.py
View license
    def process_stdin_forever(self):
        """ Yes. """
        while True:
            line = sys.stdin.readline()
            if not line:
                break
            self.raw(line)