Commit f03868bd authored by Eduardo Habkost's avatar Eduardo Habkost

python: futurize -f libfuturize.fixes.fix_print_with_import

Change all Python code to use print as a function.

This is necessary for Python 3 compatibility.

Done using:

  $ py=$( (g grep -l -E '^#!.*python';find -name '*.py' -printf '%P\n';) | \
    sort -u | grep -v README.sh4)
  $ futurize -w -f libfuturize.fixes.fix_print_with_import $py
Reviewed-by: 's avatarStefan Hajnoczi <stefanha@redhat.com>
Acked-by: 's avatarFam Zheng <famz@redhat.com>
Signed-off-by: 's avatarEduardo Habkost <ehabkost@redhat.com>
Message-Id: <20180608122952.2009-2-ehabkost@redhat.com>
[ehabkost: fixup tests/docker/docker.py]
Signed-off-by: 's avatarEduardo Habkost <ehabkost@redhat.com>
parent 0d2fa03d
This diff is collapsed.
......@@ -6,6 +6,7 @@
# Author: Alex Bennée <alex.bennee@linaro.org>
#
from __future__ import print_function
import os
import simpletrace
import argparse
......
......@@ -17,6 +17,7 @@
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, see <http://www.gnu.org/licenses/>.
from __future__ import print_function
import numpy as np
import json
import os
......@@ -162,7 +163,7 @@ class RamSection(object):
len = self.file.read64()
self.sizeinfo[self.name] = '0x%016x' % len
if self.write_memory:
print self.name
print(self.name)
mkdir_p('./' + os.path.dirname(self.name))
f = open('./' + self.name, "wb")
f.truncate(0)
......@@ -588,7 +589,7 @@ if args.extract:
dump = MigrationDump(args.file)
dump.read(desc_only = True)
print "desc.json"
print("desc.json")
f = open("desc.json", "wb")
f.truncate()
f.write(jsonenc.encode(dump.vmsd_desc))
......@@ -596,7 +597,7 @@ if args.extract:
dump.read(write_memory = True)
dict = dump.getDict()
print "state.json"
print("state.json")
f = open("state.json", "wb")
f.truncate()
f.write(jsonenc.encode(dict))
......@@ -605,10 +606,10 @@ elif args.dump == "state":
dump = MigrationDump(args.file)
dump.read(dump_memory = args.memory)
dict = dump.getDict()
print jsonenc.encode(dict)
print(jsonenc.encode(dict))
elif args.dump == "desc":
dump = MigrationDump(args.file)
dump.read(desc_only = True)
print jsonenc.encode(dump.vmsd_desc)
print(jsonenc.encode(dump.vmsd_desc))
else:
raise Exception("Please specify either -x, -d state or -d dump")
......@@ -23,6 +23,7 @@
Run QEMU with all combinations of -machine and -device types,
check for crashes and unexpected errors.
"""
from __future__ import print_function
import sys
import os
......@@ -554,7 +555,7 @@ def main():
tc[k] = v
if len(binariesToTest(args, tc)) == 0:
print >>sys.stderr, "No QEMU binary found"
print("No QEMU binary found", file=sys.stderr)
parser.print_usage(sys.stderr)
return 1
......
......@@ -12,6 +12,7 @@ Authors:
This work is licensed under the terms of the GNU GPL, version 2 or later. See
the COPYING file in the top-level directory.
"""
from __future__ import print_function
import ctypes
import struct
......
......@@ -32,6 +32,7 @@
# consuming CPU cycles. No disk I/O is performed since the ring buffer holds a
# fixed-size in-memory trace.
from __future__ import print_function
import sys
import os
......@@ -77,8 +78,8 @@ def tail_trace():
pass
def usage():
print 'Usage: %s start [buffer_size_kb] | stop | dump | tail' % sys.argv[0]
print 'Control the KVM flight recorder tracing.'
print('Usage: %s start [buffer_size_kb] | stop | dump | tail' % sys.argv[0])
print('Control the KVM flight recorder tracing.')
sys.exit(0)
def main():
......@@ -87,15 +88,15 @@ def main():
cmd = sys.argv[1]
if cmd == '--version':
print 'kvm_flightrecorder version 1.0'
print('kvm_flightrecorder version 1.0')
sys.exit(0)
if not os.path.isdir(tracing_dir):
print 'Unable to tracing debugfs directory, try:'
print 'mount -t debugfs none /sys/kernel/debug'
print('Unable to tracing debugfs directory, try:')
print('mount -t debugfs none /sys/kernel/debug')
sys.exit(1)
if not os.access(tracing_dir, os.W_OK):
print 'Unable to write to tracing debugfs directory, please run as root'
print('Unable to write to tracing debugfs directory, please run as root')
sys.exit(1)
if cmd == 'start':
......@@ -105,16 +106,16 @@ def main():
try:
buffer_size_kb = int(sys.argv[2])
except ValueError:
print 'Invalid per-cpu trace buffer size in KB'
print('Invalid per-cpu trace buffer size in KB')
sys.exit(1)
write_file(trace_path('buffer_size_kb'), str(buffer_size_kb))
print 'Per-CPU ring buffer size set to %d KB' % buffer_size_kb
print('Per-CPU ring buffer size set to %d KB' % buffer_size_kb)
start_tracing()
print 'KVM flight recorder enabled'
print('KVM flight recorder enabled')
elif cmd == 'stop':
stop_tracing()
print 'KVM flight recorder disabled'
print('KVM flight recorder disabled')
elif cmd == 'dump':
dump_trace()
elif cmd == 'tail':
......
......@@ -10,6 +10,7 @@
# This work is licensed under the terms of the GNU GPL, version 2. See
# the COPYING file in the top-level directory.
from __future__ import print_function
MSR_IA32_VMX_BASIC = 0x480
MSR_IA32_VMX_PINBASED_CTLS = 0x481
MSR_IA32_VMX_PROCBASED_CTLS = 0x482
......
......@@ -36,6 +36,7 @@
# See also: https://wiki.qemu.org/Features/QAPI/GuestAgent
#
from __future__ import print_function
import base64
import random
......
......@@ -10,6 +10,7 @@
# This work is licensed under the terms of the GNU GPLv2 or later.
# See the COPYING file in the top-level directory.
from __future__ import print_function
import sys, os
from qmp import QEMUMonitorProtocol
......@@ -26,9 +27,9 @@ def print_response(rsp, prefix=[]):
print_response(rsp[key], prefix + [key])
else:
if len(prefix):
print '%s: %s' % ('.'.join(prefix), rsp)
print('%s: %s' % ('.'.join(prefix), rsp))
else:
print '%s' % (rsp)
print('%s' % (rsp))
def main(args):
path = None
......@@ -53,21 +54,21 @@ def main(args):
elif arg in ['help']:
os.execlp('man', 'man', 'qmp')
else:
print 'Unknown argument "%s"' % arg
print('Unknown argument "%s"' % arg)
args = args[1:]
else:
break
if not path:
print "QMP path isn't set, use --path=qmp-monitor-address or set QMP_PATH"
print("QMP path isn't set, use --path=qmp-monitor-address or set QMP_PATH")
return 1
if len(args):
command, args = args[0], args[1:]
else:
print 'No command found'
print 'Usage: "qmp [--path=qmp-monitor-address] qmp-cmd arguments"'
print('No command found')
print('Usage: "qmp [--path=qmp-monitor-address] qmp-cmd arguments"')
return 1
if command in ['help']:
......@@ -93,7 +94,7 @@ def main(args):
os.execvp(fullcmd, [fullcmd] + args)
except OSError as exc:
if exc.errno == 2:
print 'Command "%s" not found.' % (fullcmd)
print('Command "%s" not found.' % (fullcmd))
return 1
raise
return 0
......@@ -104,7 +105,7 @@ def main(args):
arguments = {}
for arg in args:
if not arg.startswith('--'):
print 'Unknown argument "%s"' % arg
print('Unknown argument "%s"' % arg)
return 1
arg = arg[2:]
......
......@@ -65,6 +65,7 @@
# which will echo back the properly formatted JSON-compliant QMP that is being
# sent to QEMU, which is useful for debugging and documentation generation.
from __future__ import print_function
import qmp
import json
import ast
......@@ -153,14 +154,14 @@ class QMPShell(qmp.QEMUMonitorProtocol):
# File not found. No problem.
pass
else:
print "Failed to read history '%s'; %s" % (self._histfile, e)
print("Failed to read history '%s'; %s" % (self._histfile, e))
atexit.register(self.__save_history)
def __save_history(self):
try:
readline.write_history_file(self._histfile)
except Exception as e:
print "Failed to save history file '%s'; %s" % (self._histfile, e)
print("Failed to save history file '%s'; %s" % (self._histfile, e))
def __parse_value(self, val):
try:
......@@ -258,15 +259,15 @@ class QMPShell(qmp.QEMUMonitorProtocol):
if self._pretty:
indent = 4
jsobj = json.dumps(qmp, indent=indent)
print str(jsobj)
print(str(jsobj))
def _execute_cmd(self, cmdline):
try:
qmpcmd = self.__build_cmd(cmdline)
except Exception as e:
print 'Error while parsing command line: %s' % e
print 'command format: <command-name> ',
print '[arg-name1=arg1] ... [arg-nameN=argN]'
print('Error while parsing command line: %s' % e)
print('command format: <command-name> ', end=' ')
print('[arg-name1=arg1] ... [arg-nameN=argN]')
return True
# For transaction mode, we may have just cached the action:
if qmpcmd is None:
......@@ -275,7 +276,7 @@ class QMPShell(qmp.QEMUMonitorProtocol):
self._print(qmpcmd)
resp = self.cmd_obj(qmpcmd)
if resp is None:
print 'Disconnected'
print('Disconnected')
return False
self._print(resp)
return True
......@@ -285,12 +286,12 @@ class QMPShell(qmp.QEMUMonitorProtocol):
self.__completer_setup()
def show_banner(self, msg='Welcome to the QMP low-level shell!'):
print msg
print(msg)
if not self._greeting:
print 'Connected'
print('Connected')
return
version = self._greeting['QMP']['version']['qemu']
print 'Connected to QEMU %d.%d.%d\n' % (version['major'],version['minor'],version['micro'])
print('Connected to QEMU %d.%d.%d\n' % (version['major'],version['minor'],version['micro']))
def get_prompt(self):
if self._transmode:
......@@ -306,11 +307,11 @@ class QMPShell(qmp.QEMUMonitorProtocol):
try:
cmdline = raw_input(prompt)
except EOFError:
print
print()
return False
if cmdline == '':
for ev in self.get_events():
print ev
print(ev)
self.clear_events()
return True
else:
......@@ -366,24 +367,24 @@ class HMPShell(QMPShell):
try:
idx = int(cmdline.split()[1])
if not 'return' in self.__cmd_passthrough('info version', idx):
print 'bad CPU index'
print('bad CPU index')
return True
self.__cpu_index = idx
except ValueError:
print 'cpu command takes an integer argument'
print('cpu command takes an integer argument')
return True
resp = self.__cmd_passthrough(cmdline, self.__cpu_index)
if resp is None:
print 'Disconnected'
print('Disconnected')
return False
assert 'return' in resp or 'error' in resp
if 'return' in resp:
# Success
if len(resp['return']) > 0:
print resp['return'],
print(resp['return'], end=' ')
else:
# Error
print '%s: %s' % (resp['error']['class'], resp['error']['desc'])
print('%s: %s' % (resp['error']['class'], resp['error']['desc']))
return True
def show_banner(self):
......
......@@ -11,6 +11,7 @@
# the COPYING file in the top-level directory.
##
from __future__ import print_function
import sys
import os
from qmp import QEMUMonitorProtocol
......@@ -33,7 +34,7 @@ def usage_error(error_msg = "unspecified error"):
if len(args) > 0:
if args[0] == "-h":
print usage()
print(usage())
exit(0);
elif args[0] == "-s":
try:
......@@ -62,6 +63,6 @@ srv.connect()
rsp = srv.command('qom-get', path=path, property=prop)
if type(rsp) == dict:
for i in rsp.keys():
print '%s: %s' % (i, rsp[i])
print('%s: %s' % (i, rsp[i]))
else:
print rsp
print(rsp)
......@@ -11,6 +11,7 @@
# the COPYING file in the top-level directory.
##
from __future__ import print_function
import sys
import os
from qmp import QEMUMonitorProtocol
......@@ -33,7 +34,7 @@ def usage_error(error_msg = "unspecified error"):
if len(args) > 0:
if args[0] == "-h":
print usage()
print(usage())
exit(0);
elif args[0] == "-s":
try:
......@@ -52,13 +53,13 @@ srv = QEMUMonitorProtocol(socket_path)
srv.connect()
if len(args) == 0:
print '/'
print('/')
sys.exit(0)
for item in srv.command('qom-list', path=args[0]):
if item['type'].startswith('child<'):
print '%s/' % item['name']
print('%s/' % item['name'])
elif item['type'].startswith('link<'):
print '@%s/' % item['name']
print('@%s/' % item['name'])
else:
print '%s' % item['name']
print('%s' % item['name'])
......@@ -11,6 +11,7 @@
# the COPYING file in the top-level directory.
##
from __future__ import print_function
import sys
import os
from qmp import QEMUMonitorProtocol
......@@ -34,7 +35,7 @@ def usage_error(error_msg = "unspecified error"):
if len(args) > 0:
if args[0] == "-h":
print usage()
print(usage())
exit(0);
elif args[0] == "-s":
try:
......@@ -61,4 +62,4 @@ else:
srv = QEMUMonitorProtocol(socket_path)
srv.connect()
print srv.command('qom-set', path=path, property=prop, value=value)
print(srv.command('qom-set', path=path, property=prop, value=value))
......@@ -13,6 +13,7 @@
# the COPYING file in the top-level directory.
##
from __future__ import print_function
import sys
import os
from qmp import QEMUMonitorProtocol
......@@ -35,7 +36,7 @@ def usage_error(error_msg = "unspecified error"):
if len(args) > 0:
if args[0] == "-h":
print usage()
print(usage())
exit(0);
elif args[0] == "-s":
try:
......@@ -54,15 +55,15 @@ srv = QEMUMonitorProtocol(socket_path)
srv.connect()
def list_node(path):
print '%s' % path
print('%s' % path)
items = srv.command('qom-list', path=path)
for item in items:
if not item['type'].startswith('child<'):
try:
print ' %s: %s (%s)' % (item['name'], srv.command('qom-get', path=path, property=item['name']), item['type'])
print(' %s: %s (%s)' % (item['name'], srv.command('qom-get', path=path, property=item['name']), item['type']))
except:
print ' %s: <EXCEPTION> (%s)' % (item['name'], item['type'])
print ''
print(' %s: <EXCEPTION> (%s)' % (item['name'], item['type']))
print('')
for item in items:
if item['type'].startswith('child<'):
list_node((path if (path != '/') else '') + '/' + item['name'])
......
......@@ -18,6 +18,7 @@
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, see <http://www.gnu.org/licenses/>.
from __future__ import print_function
import argparse
import struct
from collections import namedtuple
......@@ -89,9 +90,9 @@ def call_decode(table, index, dumpfile):
"Search decode table for next step"
decoder = next((d for d in table if d.eid == index), None)
if not decoder:
print "Could not decode index: %d" % (index)
print "Entry is: %s" % (decoder)
print "Decode Table is:\n%s" % (table)
print("Could not decode index: %d" % (index))
print("Entry is: %s" % (decoder))
print("Decode Table is:\n%s" % (table))
return False
else:
return decoder.fn(decoder.eid, decoder.name, dumpfile)
......@@ -103,23 +104,23 @@ def print_event(eid, name, string=None, event_count=None):
event_count = replay_state.event_count
if string:
print "%d:%s(%d) %s" % (event_count, name, eid, string)
print("%d:%s(%d) %s" % (event_count, name, eid, string))
else:
print "%d:%s(%d)" % (event_count, name, eid)
print("%d:%s(%d)" % (event_count, name, eid))
# Decoders for each event type
def decode_unimp(eid, name, _unused_dumpfile):
"Unimplimented decoder, will trigger exit"
print "%s not handled - will now stop" % (name)
print("%s not handled - will now stop" % (name))
return False
# Checkpoint decoder
def swallow_async_qword(eid, name, dumpfile):
"Swallow a qword of data without looking at it"
step_id = read_qword(dumpfile)
print " %s(%d) @ %d" % (name, eid, step_id)
print(" %s(%d) @ %d" % (name, eid, step_id))
return True
async_decode_table = [ Decoder(0, "REPLAY_ASYNC_EVENT_BH", swallow_async_qword),
......@@ -139,8 +140,8 @@ def decode_async(eid, name, dumpfile):
async_event_checkpoint = read_byte(dumpfile)
if async_event_checkpoint != replay_state.current_checkpoint:
print " mismatch between checkpoint %d and async data %d" % (
replay_state.current_checkpoint, async_event_checkpoint)
print(" mismatch between checkpoint %d and async data %d" % (
replay_state.current_checkpoint, async_event_checkpoint))
return True
return call_decode(async_decode_table, async_event_kind, dumpfile)
......@@ -283,7 +284,7 @@ def decode_file(filename):
version = read_dword(dumpfile)
junk = read_qword(dumpfile)
print "HEADER: version 0x%x" % (version)
print("HEADER: version 0x%x" % (version))
if version == 0xe02007:
event_decode_table = v7_event_table
......
from __future__ import print_function
#
# Option ROM signing utility
#
......
......@@ -9,6 +9,7 @@
#
# For help see docs/devel/tracing.txt
from __future__ import print_function
import struct
import re
import inspect
......@@ -257,6 +258,6 @@ if __name__ == '__main__':
else:
fields.append('%s=0x%x' % (name, rec[i]))
i += 1
print ' '.join(fields)
print(' '.join(fields))
run(Formatter())
......@@ -19,6 +19,7 @@
# You should have received a copy of the GNU General Public License along
# with this program; if not, see <http://www.gnu.org/licenses/>.
from __future__ import print_function
import argparse
import json
import sys
......@@ -176,10 +177,10 @@ def check_fields(src_fields, dest_fields, desc, sec):
except StopIteration:
if d_iter_list == []:
# We were not in a substruct
print "Section \"" + sec + "\",",
print "Description " + "\"" + desc + "\":",
print "expected field \"" + s_item["field"] + "\",",
print "while dest has no further fields"
print("Section \"" + sec + "\",", end=' ')
print("Description " + "\"" + desc + "\":", end=' ')
print("expected field \"" + s_item["field"] + "\",", end=' ')
print("while dest has no further fields")
bump_taint()
break
......@@ -197,10 +198,10 @@ def check_fields(src_fields, dest_fields, desc, sec):
advance_dest = True
continue
if unused_count < 0:
print "Section \"" + sec + "\",",
print "Description \"" + desc + "\":",
print "unused size mismatch near \"",
print s_item["field"] + "\""
print("Section \"" + sec + "\",", end=' ')
print("Description \"" + desc + "\":", end=' ')
print("unused size mismatch near \"", end=' ')
print(s_item["field"] + "\"")
bump_taint()
break
continue
......@@ -211,10 +212,10 @@ def check_fields(src_fields, dest_fields, desc, sec):
advance_src = True
continue
if unused_count < 0:
print "Section \"" + sec + "\",",
print "Description \"" + desc + "\":",
print "unused size mismatch near \"",
print d_item["field"] + "\""
print("Section \"" + sec + "\",", end=' ')
print("Description \"" + desc + "\":", end=' ')
print("unused size mismatch near \"", end=' ')
print(d_item["field"] + "\"")
bump_taint()
break
continue
......@@ -262,10 +263,10 @@ def check_fields(src_fields, dest_fields, desc, sec):
unused_count = s_item["size"] - d_item["size"]
continue
print "Section \"" + sec + "\",",
print "Description \"" + desc + "\":",
print "expected field \"" + s_item["field"] + "\",",
print "got \"" + d_item["field"] + "\"; skipping rest"
print("Section \"" + sec + "\",", end=' ')
print("Description \"" + desc + "\":", end=' ')
print("expected field \"" + s_item["field"] + "\",", end=' ')
print("got \"" + d_item["field"] + "\"; skipping rest")
bump_taint()
break
......@@ -289,8 +290,8 @@ def check_subsections(src_sub, dest_sub, desc, sec):
check_descriptions(s_item, d_item, sec)
if not found:
print "Section \"" + sec + "\", Description \"" + desc + "\":",
print "Subsection \"" + s_item["name"] + "\" not found"
print("Section \"" + sec + "\", Description \"" + desc + "\":", end=' ')
print("Subsection \"" + s_item["name"] + "\" not found")
bump_taint()
......@@ -299,8 +300,8 @@ def check_description_in_list(s_item, d_item, sec, desc):
return
if not "Description" in d_item:
print "Section \"" + sec + "\", Description \"" + desc + "\",",
print "Field \"" + s_item["field"] + "\": missing description"
print("Section \"" + sec + "\", Description \"" + desc + "\",", end=' ')
print("Field \"" + s_item["field"] + "\": missing description")
bump_taint()
return
......@@ -311,17 +312,17 @@ def check_descriptions(src_desc, dest_desc, sec):
check_version(src_desc, dest_desc, sec, src_desc["name"])
if not check_fields_match(sec, src_desc["name"], dest_desc["name"]):
print "Section \"" + sec + "\":",
print "Description \"" + src_desc["name"] + "\"",
print "missing, got \"" + dest_desc["name"] + "\" instead; skipping"
print("Section \"" + sec + "\":", end=' ')
print("Description \"" + src_desc["name"] + "\"", end=' ')
print("missing, got \"" + dest_desc["name"] + "\" instead; skipping")
bump_taint()
return
for f in src_desc:
if not f in dest_desc:
print "Section \"" + sec + "\"",
print "Description \"" + src_desc["name"] + "\":",
print "Entry \"" + f + "\" missing"
print("Section \"" + sec + "\"", end=' ')
print("Description \"" + src_desc["name"] + "\":", end=' ')
print("Entry \"" + f + "\" missing")
bump_taint()
continue
......@@ -334,39 +335,39 @@ def check_descriptions(src_desc, dest_desc, sec):
def check_version(s, d, sec, desc=None):
if s["version_id"] > d["version_id"]:
print "Section \"" + sec + "\"",
print("Section \"" + sec + "\"", end=' ')
if desc:
print "Description \"" + desc + "\":",
print "version error:", s["version_id"], ">", d["version_id"]
print("Description \"" + desc + "\":", end=' ')
print("version error:", s["version_id"], ">", d["version_id"])
bump_taint()
if not "minimum_version_id" in d:
return
if s["version_id"] < d["minimum_version_id"]:
print "Section \"" + sec + "\"",
print("Section \"" + sec + "\"", end=' ')
if desc:
print "Description \"" + desc + "\":",
print "minimum version error:", s["version_id"], "<",
print d["minimum_version_id"]
print("Description \"" + desc + "\":", end=' ')
print("minimum version error:", s["version_id"], "<", end=' ')
print(d["minimum_version_id"])