当前位置: 首页>>代码示例>>Python>>正文


Python sys.stdin方法代码示例

本文整理汇总了Python中sys.stdin方法的典型用法代码示例。如果您正苦于以下问题:Python sys.stdin方法的具体用法?Python sys.stdin怎么用?Python sys.stdin使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在sys的用法示例。


在下文中一共展示了sys.stdin方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: supervisor_events

# 需要导入模块: import sys [as 别名]
# 或者: from sys import stdin [as 别名]
def supervisor_events(stdin, stdout):
    """
    An event stream from Supervisor.
    """

    while True:
        stdout.write('READY\n')
        stdout.flush()

        line = stdin.readline()
        headers = get_headers(line)

        payload = stdin.read(int(headers['len']))
        event_headers, event_data = eventdata(payload)

        yield event_headers, event_data

        stdout.write('RESULT 2\nOK')
        stdout.flush() 
开发者ID:infoxchange,项目名称:supervisor-logging,代码行数:21,代码来源:__init__.py

示例2: add_command_args

# 需要导入模块: import sys [as 别名]
# 或者: from sys import stdin [as 别名]
def add_command_args(parser):
    group = parser.add_mutually_exclusive_group()
    group.add_argument("--watch", action="store_true", help="Monitor submitted job, stream log until job completes")
    group.add_argument("--wait", action="store_true",
                       help="Block on job. Exit with code 0 if job succeeded, 1 if failed")
    group = parser.add_mutually_exclusive_group()
    group.add_argument("--command", nargs="+", help="Run these commands as the job (using " + BOLD("bash -c") + ")")
    group.add_argument("--execute", type=argparse.FileType("rb"), metavar="EXECUTABLE",
                       help="Read this executable file and run it as the job")
    group.add_argument("--wdl", type=argparse.FileType("rb"), metavar="WDL_WORKFLOW",
                       help="Read this WDL workflow file and run it as the job")
    parser.add_argument("--wdl-input", type=argparse.FileType("r"), metavar="WDL_INPUT_JSON", default=sys.stdin,
                        help="With --wdl, use this JSON file as the WDL job input (default: stdin)")
    parser.add_argument("--environment", nargs="+", metavar="NAME=VALUE",
                        type=lambda x: dict(zip(["name", "value"], x.split("=", 1))), default=[])
    parser.add_argument("--staging-s3-bucket", help=argparse.SUPPRESS) 
开发者ID:kislyuk,项目名称:aegea,代码行数:18,代码来源:batch.py

示例3: _sender

# 需要导入模块: import sys [as 别名]
# 或者: from sys import stdin [as 别名]
def _sender(conn,stdin):
    # Warning: when the parent dies we are seeing continual
    # newlines, so we only access so many before stopping
    counter = 0

    while True:
        try:
            line = stdin.readline().strip()

            if line == "":
                counter += 1
                if counter > 100:
                    break
                continue
            counter = 0

            conn.send(line)

            sendLogger.debug(line)

        except:
            pass 
开发者ID:sdn-ixp,项目名称:iSDX,代码行数:24,代码来源:client.py

示例4: _fopen

# 需要导入模块: import sys [as 别名]
# 或者: from sys import stdin [as 别名]
def _fopen(fname, mode):
    """
    Extend file open function, to support 
        1) "-", which means stdin/stdout
        2) "$cmd |" which means pipe.stdout
    """
    if mode not in ["w", "r", "wb", "rb"]:
        raise ValueError("Unknown open mode: {mode}".format(mode=mode))
    if not fname:
        return None
    fname = fname.rstrip()
    if fname == "-":
        if mode in ["w", "wb"]:
            return sys.stdout.buffer if mode == "wb" else sys.stdout
        else:
            return sys.stdin.buffer if mode == "rb" else sys.stdin
    elif fname[-1] == "|":
        pin = pipe_fopen(fname[:-1], mode, background=(mode == "rb"))
        return pin if mode == "rb" else TextIOWrapper(pin)
    else:
        if mode in ["r", "rb"] and not os.path.exists(fname):
            raise FileNotFoundError(
                "Could not find common file: {}".format(fname))
        return open(fname, mode) 
开发者ID:funcwj,项目名称:kaldi-python-io,代码行数:26,代码来源:inst.py

示例5: build

# 需要导入模块: import sys [as 别名]
# 或者: from sys import stdin [as 别名]
def build(args):
    words={}

    for line in sys.stdin:
        line=line.strip()
        if not line or line.startswith("#"):
            continue
        cols=line.split("\t")
        word=(cols[FORM], cols[UPOS], cols[XPOS], cols[FEATS], cols[LEMMA])
        if word not in words:
            words[word]=0
        words[word]+=1

    for word, count in sorted(words.items(), key=lambda x: x[1], reverse=True):

        if count>args.cutoff:
            w="\t".join(word)
            if len(w.strip().split("\t"))!=5: # make sure there is no empty columns
                print("Skipping weird line", w, file=sys.stderr)
                continue
            print(w)
        else:
            break 
开发者ID:TurkuNLP,项目名称:Turku-neural-parser-pipeline,代码行数:25,代码来源:build_lemma_cache.py

示例6: hciCallback

# 需要导入模块: import sys [as 别名]
# 或者: from sys import stdin [as 别名]
def hciCallback(self, record):
                hcipkt, orig_len, inc_len, flags, drops, recvtime = record

                dummy = "\x00\x00\x00"      # TODO: Figure out purpose of these fields
                direction = p8(flags & 0x01)
                packet = dummy + direction + hcipkt.getRaw()
                length = len(packet)
                ts_sec =  recvtime.second #+ timestamp.minute*60 + timestamp.hour*60*60 #FIXME timestamp not set
                ts_usec = recvtime.microsecond
                pcap_packet = struct.pack('@ I I I I', ts_sec, ts_usec, length, length) + packet
                try:
                    self.wireshark_process.stdin.write(pcap_packet)
                    self.wireshark_process.stdin.flush()
                    log.debug("HciMonitorController._callback: done")
                except IOError as e:
                    log.warn("HciMonitorController._callback: broken pipe. terminate.")
                    self.killMonitor() 
开发者ID:francozappa,项目名称:knob,代码行数:19,代码来源:cmds.py

示例7: lmpCallback

# 需要导入模块: import sys [as 别名]
# 或者: from sys import stdin [as 别名]
def lmpCallback(self, lmp_packet, sendByOwnDevice, src, dest, timestamp):
                eth_header = dest + src + "\xff\xf0"
                meta_data  = "\x00"*6 if sendByOwnDevice else "\x01\x00\x00\x00\x00\x00"
                packet_header = "\x19\x00\x00" + p8(len(lmp_packet)<<3 | 7)

                packet = eth_header + meta_data + packet_header + lmp_packet
                packet += "\x00\x00" # CRC
                length = len(packet)
                ts_sec =  timestamp.second + timestamp.minute*60 + timestamp.hour*60*60
                ts_usec = timestamp.microsecond
                pcap_packet = struct.pack('@ I I I I', ts_sec, ts_usec, length, length) + packet
                try:
                    self.wireshark_process.stdin.write(pcap_packet)
                    self.wireshark_process.stdin.flush()
                    log.debug("LmpMonitorController._callback: done")
                except IOError as e:
                    log.warn("LmpMonitorController._callback: broken pipe. terminate.")
                    self.killMonitor() 
开发者ID:francozappa,项目名称:knob,代码行数:20,代码来源:cmds.py

示例8: main

# 需要导入模块: import sys [as 别名]
# 或者: from sys import stdin [as 别名]
def main():
    # Initialize the logger
    logging.basicConfig()

    # Intialize from our arguments
    insightfinder = InsightfinderStore(*sys.argv[1:])

    current_chunk = 0

    # Get all the inputs
    for line in sys.stdin:
        if insightfinder.filter_string not in line:
            continue
        map_size = len(bytearray(json.dumps(insightfinder.metrics_map)))
        if map_size >= insightfinder.flush_kb * 1000:
            insightfinder.logger.debug("Flushing chunk number: " + str(current_chunk))
            insightfinder.send_metrics()
            current_chunk += 1
        insightfinder.append(line.strip())
    insightfinder.logger.debug("Flushing chunk number: " + str(current_chunk))
    insightfinder.send_metrics()
    insightfinder.save_grouping()
    insightfinder.logger.debug("Finished sending all chunks to InsightFinder") 
开发者ID:insightfinder,项目名称:InsightAgent,代码行数:25,代码来源:insightfinder.py

示例9: __call__

# 需要导入模块: import sys [as 别名]
# 或者: from sys import stdin [as 别名]
def __call__(self, string):
            # the special argument "-" means sys.std{in,out}
            if string == '-':
                if 'r' in self._mode:
                    return sys.stdin
                elif 'w' in self._mode:
                    return sys.stdout
                else:
                    msg = _('argument "-" with mode %r') % self._mode
                    raise ValueError(msg)

            # all other arguments are used as file names
            try:
                return open(string, self._mode, self._bufsize, self._encoding, self._errors)
            except OSError as e:
                message = _("can't open '%s': %s")
                raise ArgumentTypeError(message % (string, e)) 
开发者ID:nojanath,项目名称:SublimeKSP,代码行数:19,代码来源:ksp_compiler.py

示例10: _token_to_filenames

# 需要导入模块: import sys [as 别名]
# 或者: from sys import stdin [as 别名]
def _token_to_filenames(token):
        if token[0] == '!':
            pattern = token[1:]
            filenames = glob.glob(pattern)
            if not filenames:
                raise RuntimeError('No filenames matched "%s" pattern' % pattern)
        elif token[0] == '@':
            filelist_name = sys.stdin if token == '@-' else token[1:]
            with open(filelist_name) as filelist:
                filenames = [line.rstrip('\n') for line in filelist]
            directory = os.path.dirname(token[1:])
            if directory != '.':
                filenames = [f if f[0] != '/' else directory + '/' + f for f in filenames]
        else:
            filenames = [token]
        return filenames 
开发者ID:udapi,项目名称:udapi-python,代码行数:18,代码来源:files.py

示例11: next_filehandle

# 需要导入模块: import sys [as 别名]
# 或者: from sys import stdin [as 别名]
def next_filehandle(self):
        """Go to the next file and retrun its filehandle or None (meaning no more files)."""
        filename = self.next_filename()
        if filename is None:
            fhandle = None
        elif filename == '-':
            fhandle = io.TextIOWrapper(sys.stdin.buffer, encoding=self.encoding)
        elif filename == '<filehandle_input>':
            fhandle = self.filehandle
        else:
            filename_extension = filename.split('.')[-1]
            if filename_extension == 'gz':
                myopen = gzip.open
            elif filename_extension == 'xz':
                myopen = lzma.open
            elif filename_extension == 'bz2':
                myopen = bz2.open
            else:
                myopen = open
            fhandle = myopen(filename, 'rt', encoding=self.encoding)
        self.filehandle = fhandle
        return fhandle 
开发者ID:udapi,项目名称:udapi-python,代码行数:24,代码来源:files.py

示例12: description_of

# 需要导入模块: import sys [as 别名]
# 或者: from sys import stdin [as 别名]
def description_of(lines, name='stdin'):
    """
    Return a string describing the probable encoding of a file or
    list of strings.

    :param lines: The lines to get the encoding of.
    :type lines: Iterable of bytes
    :param name: Name of file or collection of lines
    :type name: str
    """
    u = UniversalDetector()
    for line in lines:
        u.feed(line)
    u.close()
    result = u.result
    if result['encoding']:
        return '{0}: {1} with confidence {2}'.format(name, result['encoding'],
                                                     result['confidence'])
    else:
        return '{0}: no result'.format(name) 
开发者ID:war-and-code,项目名称:jawfish,代码行数:22,代码来源:chardetect.py

示例13: redirect_output

# 需要导入模块: import sys [as 别名]
# 或者: from sys import stdin [as 别名]
def redirect_output(self, statement):
        if statement.parsed.pipeTo:
            self.kept_state = Statekeeper(self, ('stdout',))
            self.kept_sys = Statekeeper(sys, ('stdout',))
            self.redirect = subprocess.Popen(statement.parsed.pipeTo, shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE)
            sys.stdout = self.stdout = self.redirect.stdin
        elif statement.parsed.output:
            if (not statement.parsed.outputTo) and (not can_clip):
                raise EnvironmentError('Cannot redirect to paste buffer; install ``xclip`` and re-run to enable')
            self.kept_state = Statekeeper(self, ('stdout',))
            self.kept_sys = Statekeeper(sys, ('stdout',))
            if statement.parsed.outputTo:
                mode = 'w'
                if statement.parsed.output == 2 * self.redirector:
                    mode = 'a'
                sys.stdout = self.stdout = open(os.path.expanduser(statement.parsed.outputTo), mode)
            else:
                sys.stdout = self.stdout = tempfile.TemporaryFile(mode="w+")
                if statement.parsed.output == '>>':
                    self.stdout.write(get_paste_buffer()) 
开发者ID:OpenTrading,项目名称:OpenTrader,代码行数:22,代码来源:cmd2plus.py

示例14: do_load

# 需要导入模块: import sys [as 别名]
# 或者: from sys import stdin [as 别名]
def do_load(self, arg=None):
        """Runs script of command(s) from a file or URL."""
        if arg is None:
            targetname = self.default_file_name
        else:
            arg = arg.split(None, 1)
            targetname, args = arg[0], (arg[1:] or [''])[0].strip()
        try:
            target = self.read_file_or_url(targetname)
        except IOError as e:
            self.perror('Problem accessing script from %s: \n%s' % (targetname, e))
            return
        keepstate = Statekeeper(self, ('stdin','use_rawinput','prompt',
                                       'continuation_prompt','current_script_dir'))
        self.stdin = target
        self.use_rawinput = False
        self.prompt = self.continuation_prompt = ''
        self.current_script_dir = os.path.split(targetname)[0]
        stop = self._cmdloop()
        self.stdin.close()
        keepstate.restore()
        self.lastcmd = ''
        return stop and (stop != self._STOP_SCRIPT_NO_EXIT) 
开发者ID:OpenTrading,项目名称:OpenTrader,代码行数:25,代码来源:cmd2plus.py

示例15: in_idle

# 需要导入模块: import sys [as 别名]
# 或者: from sys import stdin [as 别名]
def in_idle():
    """
    @rtype: C{boolean}
    @return: true if this function is run within idle.  Tkinter
    programs that are run in idle should never call L{Tk.mainloop}; so
    this function should be used to gate all calls to C{Tk.mainloop}.

    @warning: This function works by checking C{sys.stdin}.  If the
    user has modified C{sys.stdin}, then it may return incorrect
    results.
    """
    import sys, types
    return (type(sys.stdin) == types.InstanceType and \
            sys.stdin.__class__.__name__ == 'PyShell')

##//////////////////////////////////////////////////////
##  Test code.
##////////////////////////////////////////////////////// 
开发者ID:rafasashi,项目名称:razzy-spinner,代码行数:20,代码来源:__init__.py


注:本文中的sys.stdin方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。