Skip to content

Commit

Permalink
lib: correctly handle stdin/stdout (Python 3)
Browse files Browse the repository at this point in the history
This changes stdin to be opened as binary if the input is not a tty.

This changes stdout to be opened as binary if encoding or if the output
is not a tty.

Signed-off-by: Adrian Reber <areber@redhat.com>
  • Loading branch information
adrianreber authored and avagin committed Sep 3, 2021
1 parent 9635d64 commit bf80fee
Showing 1 changed file with 20 additions and 6 deletions.
26 changes: 20 additions & 6 deletions lib/py/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,28 @@ def inf(opts):
if opts['in']:
return open(opts['in'], 'rb')
else:
return sys.stdin
if (sys.version_info < (3, 0)):
return sys.stdin
if sys.stdin.isatty():
# If we are reading from a terminal (not a pipe) we want text input and not binary
return sys.stdin
return sys.stdin.buffer


def outf(opts):
def outf(opts, decode):
# Decode means from protobuf to JSON.
# Use text when writing to JSON else use binaray mode
if opts['out']:
return open(opts['out'], 'wb+')
mode = 'wb+'
if decode:
mode = 'w+'
return open(opts['out'], mode)
else:
return sys.stdout
if (sys.version_info < (3, 0)):
return sys.stdout
if decode:
return sys.stdout
return sys.stdout.buffer


def dinf(opts, name):
Expand All @@ -39,15 +53,15 @@ def decode(opts):
if opts['pretty']:
indent = 4

f = outf(opts)
f = outf(opts, True)
json.dump(img, f, indent=indent)
if f == sys.stdout:
f.write("\n")


def encode(opts):
img = json.load(inf(opts))
pycriu.images.dump(img, outf(opts))
pycriu.images.dump(img, outf(opts, False))


def info(opts):
Expand Down

0 comments on commit bf80fee

Please sign in to comment.