Python sys.stdin 模块,readline() 实例源码
我们从Python开源项目中,提取了以下24个代码示例,用于说明如何使用sys.stdin.readline()。
def readcase():
nshuffles = int(stdin.readline())
# Read all shuffles into a single list and then split them,because
# a shuffle Could extend more than one line
all_shuffles = []
while len(all_shuffles)<nshuffles*52:
all_shuffles.extend(readnum())
shuffles = []
for i in range(nshuffles):
shuffles.append(all_shuffles[i*52:(i+1)*52])
# Read shuffles observed
observed = []
while True:
try:
seen = int(stdin.readline())
observed.append(seen)
except Exception:
break #Found empty line
return shuffles, observed
def loadcase():
# discard empty line
_ = stdin.readline()
# Ferry length in cm
length = int(stdin.readline())*100
# Read car dimmensions until 0 is reached
cars = []
car = int(stdin.readline())
while car>0:
cars.append(car)
car = int(stdin.readline())
return length, cars
def read_line(self):
"""Read and return the next DDS log message from the device.
Return None on EOF or error.
"""
line = None
try:
line = stdin.readline()
if line == "": # On EOF it'll be empty,for empty line it's \n
line = None
except Exception as ex: # pylint: disable=W0703
# On error don't return None because we want to continue reading.
line = ""
print("[InputError] %s" % ex)
if self.show_progress:
self.print_time(0.2)
return line
def read_line(self):
"""Read and return the next DDS log message from the device.
Return None on EOF or error.
"""
line = None
try:
line = self.stream.readline()
if line == "": # On EOF it'll be empty,for empty line it's \n
line = None
except Exception as ex: # pylint: disable=W0703
# On error don't return None because we want to continue reading.
line = ""
print("[InputError] %s" % ex)
if self.show_progress:
self.print_progress(0.01, 2, 51)
return line
def main():
timings = False
start = time.time()
initialize()
if timings: print('initialize {} s'.format(time.time() - start), file=stderr)
start = time.time()
command_table = load_command_table()
if timings: print('load_command_table {} s'.format(time.time() - start), file=stderr)
start = time.time()
group_index = get_group_index(command_table)
if timings: print('get_group_index {} s'.format(time.time() - start), file=stderr)
start = time.time()
snippets = get_snippets(command_table) if AUTOMATIC_SNIPPETS_ENABLED else []
if timings: print('get_snippets {} s'.format(time.time() - start), file=stderr)
while True:
line = stdin.readline()
start = time.time()
request = json.loads(line)
response_data = None
if request['data'].get('request') == 'status':
response_data = get_status()
if timings: print('get_status {} s'.format(time.time() - start), file=stderr)
elif request['data'].get('request') == 'hover':
response_data = get_hover_text(group_index, command_table, request['data']['command'])
if timings: print('get_hover_text {} s'.format(time.time() - start), file=stderr)
else:
response_data = get_completions(group_index, snippets, request['data'], True)
if timings: print('get_completions {} s'.format(time.time() - start), file=stderr)
response = {
'sequence': request['sequence'],
'data': response_data
}
output = json.dumps(response)
stdout.write(output + '\n')
stdout.flush()
stderr.flush()
def readarray(typ):
return list(map(typ, stdin.readline().split()))
def _readarray(f):
return tuple(map(f, stdin.readline().split()))
# snip{ discrete_binary_search
def readnum():
return list(map(int, stdin.readline().split()))
def readnum():
return list(map(int, stdin.readline().split()))
def readhand():
"""Read next hand into back a white hands"""
both_hands = stdin.readline().split()
if not both_hands:
return None, None
both_hands = [Card(v, s) for v, s in both_hands]
black_hand, white_hand = both_hands[:5], both_hands[5:]
return black_hand, white_hand
def load_pair():
return tuple(map(int, stdin.readline().split()))
def readnum():
return list(map(int, stdin.readline().split()))
def readstick():
"""Read one stick problem form stdin"""
length = int(stdin.readline())
if not length:
return None, None
ncuts = int(stdin.readline())
cuts = list(map(int, stdin.readline().split()))
return length, cuts
def readcase():
return stdin.readline().rstrip(), stdin.readline().rstrip()
def main():
# Parse cmdline into opts namespace
opts = parse_cmdline()
# Might as well name logger based on tag
myLogger = logging.getLogger(opts.tag)
# Set threshold as low as possible
myLogger.setLevel(logging.DEBUG)
# Instantiate handler as udp or tcp or plain local syslog
if opts.udp:
myHandler = logging.handlers.SysLogHandler(address=(opts.server, opts.port), facility=opts.facility, socktype=SOCK_DGRAM)
elif opts.tcp:
myHandler = logging.handlers.SysLogHandler(address=(opts.server, socktype=SOCK_STREAM)
else:
myHandler = logging.handlers.SysLogHandler(address=opts.socket, facility=opts.facility)
# Use custom priority_map
myHandler.priority_map = loggerSyslogHandlerPriorityMap
# Determine whether to print [ID] after tag
if opts.pid or opts.id is not None:
if opts.id:
# Print TAG[CUSTOM_ID] (passed via --id=xxx)
myFormatter = logging.Formatter('%(name)s[{0}]: %(message)s'.format(opts.id))
else:
# Print TAG[PID] (due to -i or --id)
myFormatter = logging.Formatter('%(name)s[%(process)s]: %(message)s')
elif opts.ppid:
# Print TAG[PPID] (due to --ppid)
myFormatter = logging.Formatter('%(name)s[{0}]: %(message)s'.format(getppid()))
else:
# Print just TAG
myFormatter = logging.Formatter('%(name)s: %(message)s')
# Add formatter to handler
myHandler.setFormatter(myFormatter)
# Add handler to logger
myLogger.addHandler(myHandler)
# What to log ...
if opts.file:
# If passed a file,log each line from file
for line in opts.file:
if opts.skip_empty and not line.strip():
continue
myLogger.log(opts.level, line)
elif opts.message:
# If passed a message on the cmdline,log that instead
myLogger.log(opts.level, " ".join(opts.message))
else:
# Otherwise,log each line of stdin until receive EOF (Ctrl-d)
while 1:
line = stdin.readline()
if not line:
break
myLogger.log(opts.level, line)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。