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.
149 Examples
4
Example 1
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))
4
Example 2
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()
3
Example 3
Project: pyxc-pj Source File: main.py
def codeToCode():
py = sys.stdin.read()
try:
js = pj.api_internal.codeToCode(py)
sys.stdout.write(js)
except Exception as e:
writeExceptionJsonAndDie(e)
3
Example 4
Project: dogapi Source File: dashboard.py
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))
3
Example 5
def debug():
v = VT100(142, 32, debug=True)
data = sys.stdin.read()
print('-= begin input =-')
print(repr(data))
print('-= begin parsing =-')
for b in data:
v.append(b)
print('-= begin dump =-')
print(repr(v.dump()))
print('-= begin output =-')
sys.stdout.write(v.dump())
3
Example 6
Project: bacpypes Source File: extended_tag_list.py
@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()
3
Example 7
Project: clustershell Source File: Clush.py
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)
3
Example 8
def main():
parser = argparse.ArgumentParser(description='A simple Python library designed to make it quick and easy to '
'represent tabular data in visually appealing ASCII tables.')
parser.add_argument('--csv', help='CSV file name')
parser.add_argument('--md', help='Markdown file name')
parser.add_argument('--rst', help='reStructuredText file name')
args = parser.parse_args()
if args.csv:
with open(args.csv) as fp:
print(from_csv(fp))
elif args.md:
with open(args.md) as md:
print(from_md(md.read()))
else:
text_in = sys.stdin.read()
print(from_csv(StringIO.StringIO(text_in)))
3
Example 9
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)
3
Example 10
Project: pyfs Source File: scriptsupport.py
def get_line_from_stdin():
buff = ''
while True:
ch = sys.stdin.read(1)
if len(ch) == 0: # end of file
break
if ch != "\n":
buff += ch
else:
yield buff
buff = ''
3
Example 11
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
3
Example 12
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
3
Example 13
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")
3
Example 14
Project: wikiclass Source File: score.py
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))
3
Example 15
def process(self):
while True:
buf = sys.stdin.read(self.buffer_size)
if buf == "":
break
self.xml_parser.Parse(buf)
3
Example 16
Project: conary Source File: keymgmt.py
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)
3
Example 17
Project: pycopia Source File: xmodem.py
def getc(size, timeout=10):
try:
data = scheduler.iotimeout(sys.stdin.read, (size,), timeout=timeout)
except scheduler.TimeoutError:
return None
else:
return data
3
Example 18
Project: clevercss Source File: ccss.py
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)
3
Example 19
Project: goopg Source File: chrome-main.py
def read_bundle():
"""Helper that reads bundles from the webapp."""
# Read the bundle length (first 4 bytes).
text_length_bytes = sys.stdin.read(4)
# Unpack bundle length as 4 byte integer.
text_length = struct.unpack('i', text_length_bytes)[0]
# Read the text (JSON object) of the bundle.
raw_text = sys.stdin.read(text_length).decode('utf-8')
return json.loads(raw_text)
3
Example 20
def read_data(self, filename):
try:
if filename == '-':
data = sys.stdin.read()
else:
with open(filename, "rb") as fh:
data = fh.read()
except Exception as e:
raise AnsibleError(str(e))
return data
3
Example 21
def run():
p = JavaScriptPacker()
#script = open('test_plone.js').read()
script = sys.stdin.read()
result = p.pack(script, encoding=62, fastDecode=True)
#open('output.js','w').write(result)
print result
3
Example 22
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
3
Example 23
Project: sensu-py Source File: utils.py
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
3
Example 24
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")
3
Example 25
Project: pygtrie Source File: example.py
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)
3
Example 26
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")
3
Example 27
Project: simian Source File: runtime.py
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()
3
Example 28
Project: astack Source File: astack.py
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()
3
Example 29
Project: InspectorD Source File: ejabberd_auth.py
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
3
Example 30
Project: FanFicFare Source File: utils.py
def wrap_read(): # pragma: no cover
"""
:rtype: str
"""
try:
return sys.stdin.read()
except AttributeError:
return sys.stdin.buffer.read()
3
Example 31
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)
3
Example 32
Project: llvm-p86 Source File: pre.py
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
3
Example 33
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
3
Example 34
Project: pyjvm Source File: vmo.py
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))
3
Example 35
Project: pyflakes Source File: api.py
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)
3
Example 36
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")
3
Example 37
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
3
Example 38
Project: RPi-chromium Source File: run_omxplayer.py
def read_thread_func():
message_number = 0
# Read the message length (first 4 bytes).
text_length_bytes = sys.stdin.read(4)
# Unpack message length as 4 byte integer.
text_length = struct.unpack('i', text_length_bytes)[0]
# Read the text (JSON object) of the message.
text = sys.stdin.read(text_length).decode('utf-8')
return text
3
Example 39
Project: thundergate Source File: linux_fun.py
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)
3
Example 40
def process(input=None, output=None, *args, **kwargs):
if input is None:
filename = "-"
input = sys.stdin.read()
else:
filename = input
with open(input, "rb") as fh:
input = fh.read().decode("UTF-8")
kwargs["preprocessor"] = partial(DirectoryPreprocessor, kwargs.pop("template_dir", None))
result = process_text(input, filename, *args, **kwargs)
if sys.version < '3':
result = result.encode("UTF-8")
if output is None:
sys.stdout.write(result)
else:
with open(output, "w") as fh:
fh.write(result)
3
Example 41
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
3
Example 42
Project: synnefo Source File: _common.py
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)
3
Example 43
Project: deimos Source File: proto.py
@staticmethod
def read(cls):
unpacked = struct.unpack('I', sys.stdin.read(4))
size = unpacked[0]
if size <= 0:
raise Err("Expected non-zero size for Protobuf")
data = sys.stdin.read(size)
if len(data) != size:
raise Err("Expected %d bytes; received %d", size, len(data))
return deserialize(cls, data)
3
Example 44
Project: cstar_perf Source File: render.py
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)
3
Example 45
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))
3
Example 46
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 = {}
3
Example 47
Project: flake8 Source File: utils.py
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()
3
Example 48
Project: ficloud Source File: host.py
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')
3
Example 49
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))
3
Example 50
Project: pyhackedit Source File: api.py
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)