提交 06138453 编写于 作者: X Xu Han

Python 3: Miscellaneous fixes

Signed-off-by: NXu Han <xuhan@redhat.com>
上级 602f5c31
...@@ -8,9 +8,9 @@ if len(sys.argv) > 1: ...@@ -8,9 +8,9 @@ if len(sys.argv) > 1:
fd = os.open(sys.argv[1], os.O_RDONLY | os.O_NONBLOCK) fd = os.open(sys.argv[1], os.O_RDONLY | os.O_NONBLOCK)
if CDROM.CDS_TRAY_OPEN == fcntl.ioctl(fd, CDROM.CDROM_DRIVE_STATUS): if CDROM.CDS_TRAY_OPEN == fcntl.ioctl(fd, CDROM.CDROM_DRIVE_STATUS):
print "cdrom is open" print("cdrom is open")
else: else:
print "cdrom is close" print("cdrom is close")
os.close(fd) os.close(fd)
else: else:
...@@ -19,6 +19,6 @@ if len(sys.argv) > 1: ...@@ -19,6 +19,6 @@ if len(sys.argv) > 1:
ctypes.windll.WINMM.mciSendStringW(msg, None, 0, None) ctypes.windll.WINMM.mciSendStringW(msg, None, 0, None)
msg = u"status d_drive length" msg = u"status d_drive length"
if ctypes.windll.WINMM.mciSendStringW(msg, None, 0, None) == 0: if ctypes.windll.WINMM.mciSendStringW(msg, None, 0, None) == 0:
print "cdrom is close" print("cdrom is close")
else: else:
print "cdrom is open" print("cdrom is open")
...@@ -14,7 +14,7 @@ import getopt ...@@ -14,7 +14,7 @@ import getopt
def daemonize(output_file): def daemonize(output_file):
try: try:
pid = os.fork() pid = os.fork()
except OSError, e: except OSError as e:
raise Exception("error %d: %s" % (e.strerror, e.errno)) raise Exception("error %d: %s" % (e.strerror, e.errno))
if pid: if pid:
...@@ -26,12 +26,12 @@ def daemonize(output_file): ...@@ -26,12 +26,12 @@ def daemonize(output_file):
sys.stderr.flush() sys.stderr.flush()
if output_file: if output_file:
output_handle = file(output_file, 'a+', 0) output_handle = open(output_file, 'a+', 0)
# autoflush stdout/stderr # autoflush stdout/stderr
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
sys.stderr = os.fdopen(sys.stderr.fileno(), 'w', 0) sys.stderr = os.fdopen(sys.stderr.fileno(), 'w', 0)
else: else:
output_handle = file('/dev/null', 'a+') output_handle = open('/dev/null', 'a+')
stdin_handle = open('/dev/null', 'r') stdin_handle = open('/dev/null', 'r')
os.dup2(output_handle.fileno(), sys.stdout.fileno()) os.dup2(output_handle.fileno(), sys.stdout.fileno())
...@@ -70,9 +70,9 @@ def run_server(host, port, daemon, path, queue_size, threshold, drift): ...@@ -70,9 +70,9 @@ def run_server(host, port, daemon, path, queue_size, threshold, drift):
prev_check_timestamp = local_timestamp prev_check_timestamp = local_timestamp
if verbose: if verbose:
if check_drift: if check_drift:
print "%.2f: %s (%s)" % (local_timestamp, heartbeat, drift) print("%.2f: %s (%s)" % (local_timestamp, heartbeat, drift))
else: else:
print "%.2f: %s" % (local_timestamp, heartbeat) print("%.2f: %s" % (local_timestamp, heartbeat))
def run_client(host, port, daemon, path, interval): def run_client(host, port, daemon, path, interval):
...@@ -87,9 +87,10 @@ def run_client(host, port, daemon, path, interval): ...@@ -87,9 +87,10 @@ def run_client(host, port, daemon, path, interval):
sock.sendall(heartbeat) sock.sendall(heartbeat)
sock.close() sock.close()
if verbose: if verbose:
print heartbeat print(heartbeat)
except socket.error, (value, message): except socket.error as message:
print "%.2f: ERROR, %d - %s" % (float(time.time()), value, message) print("%.2f: ERROR - %s"
% (float(time.time()), message))
seq += 1 seq += 1
time.sleep(interval) time.sleep(interval)
...@@ -102,16 +103,16 @@ def get_heartbeat(seq=1): ...@@ -102,16 +103,16 @@ def get_heartbeat(seq=1):
def check_heartbeat(heartbeat, local_timestamp, threshold, check_drift): def check_heartbeat(heartbeat, local_timestamp, threshold, check_drift):
hostname, _, timestamp = heartbeat.rsplit() hostname, _, timestamp = heartbeat.rsplit()
timestamp = float(timestamp) timestamp = float(timestamp)
if client_prev_timestamp.has_key(hostname): if hostname in client_prev_timestamp:
delta = local_timestamp - client_prev_timestamp[hostname] delta = local_timestamp - client_prev_timestamp[hostname]
if delta > threshold: if delta > threshold:
print ("%.2f: ALERT, SLU detected on host %s, delta %ds" % print("%.2f: ALERT, SLU detected on host %s, delta %ds" %
(float(time.time()), hostname, delta)) (float(time.time()), hostname, delta))
client_prev_timestamp[hostname] = local_timestamp client_prev_timestamp[hostname] = local_timestamp
if check_drift: if check_drift:
if not client_clock_offset.has_key(hostname): if hostname not in client_clock_offset:
client_clock_offset[hostname] = timestamp - local_timestamp client_clock_offset[hostname] = timestamp - local_timestamp
client_prev_drift[hostname] = 0 client_prev_drift[hostname] = 0
drift = timestamp - local_timestamp - client_clock_offset[hostname] drift = timestamp - local_timestamp - client_clock_offset[hostname]
...@@ -127,8 +128,8 @@ def check_for_timeouts(threshold, check_drift): ...@@ -127,8 +128,8 @@ def check_for_timeouts(threshold, check_drift):
timestamp = client_prev_timestamp[hostname] timestamp = client_prev_timestamp[hostname]
delta = local_timestamp - timestamp delta = local_timestamp - timestamp
if delta > threshold * 2: if delta > threshold * 2:
print ("%.2f: ALERT, SLU detected on host %s, no heartbeat for %ds" print("%.2f: ALERT, SLU detected on host %s, no heartbeat for %ds"
% (local_timestamp, hostname, delta)) % (local_timestamp, hostname, delta))
del client_prev_timestamp[hostname] del client_prev_timestamp[hostname]
if check_drift: if check_drift:
del client_clock_offset[hostname] del client_clock_offset[hostname]
...@@ -136,7 +137,7 @@ def check_for_timeouts(threshold, check_drift): ...@@ -136,7 +137,7 @@ def check_for_timeouts(threshold, check_drift):
def usage(): def usage():
print """ print("""
Usage: Usage:
heartbeat_slu.py --server --address <bind_address> --port <bind_port> heartbeat_slu.py --server --address <bind_address> --port <bind_port>
...@@ -146,7 +147,7 @@ Usage: ...@@ -146,7 +147,7 @@ Usage:
heartbeat_slu.py --client --address <server_address> -p <server_port> heartbeat_slu.py --client --address <server_address> -p <server_port>
[--file output_file] [--no-daemon] [--verbose] [--file output_file] [--no-daemon] [--verbose]
[--interval <heartbeat interval in seconds>] [--interval <heartbeat interval in seconds>]
""" """)
# host information and global data # host information and global data
...@@ -175,8 +176,8 @@ try: ...@@ -175,8 +176,8 @@ try:
"server", "client", "no-daemon", "address=", "port=", "server", "client", "no-daemon", "address=", "port=",
"file=", "server", "interval=", "threshold=", "verbose", "file=", "server", "interval=", "threshold=", "verbose",
"check-drift", "help"]) "check-drift", "help"])
except getopt.GetoptError, e: except getopt.GetoptError as e:
print "error: %s" % str(e) print("error: %s" % str(e))
usage() usage()
sys.exit(1) sys.exit(1)
...@@ -205,7 +206,7 @@ for param, value in opts: ...@@ -205,7 +206,7 @@ for param, value in opts:
usage() usage()
sys.exit(0) sys.exit(0)
else: else:
print "error: unrecognized option: %s" % value print("error: unrecognized option: %s" % value)
usage() usage()
sys.exit(1) sys.exit(1)
......
...@@ -80,7 +80,7 @@ parser.add_option("--tarball", dest="tarballLocation", ...@@ -80,7 +80,7 @@ parser.add_option("--tarball", dest="tarballLocation",
(options, args) = parser.parse_args() (options, args) = parser.parse_args()
if not options.pkgName: if not options.pkgName:
print "Missing required arguments" print("Missing required arguments")
parser.print_help() parser.print_help()
sys.exit(1) sys.exit(1)
...@@ -98,7 +98,7 @@ if options.gitRepo: ...@@ -98,7 +98,7 @@ if options.gitRepo:
f = open("/etc/redhat-release", "r") f = open("/etc/redhat-release", "r")
rhelVersion = f.read() rhelVersion = f.read()
print "OS: %s" % rhelVersion print("OS: %s" % rhelVersion)
if re.findall("release 6", rhelVersion): if re.findall("release 6", rhelVersion):
if pkgName in ("spice-gtk", "virt-viewer"): if pkgName in ("spice-gtk", "virt-viewer"):
autogen_options[pkgName] += " --with-gtk=2.0" autogen_options[pkgName] += " --with-gtk=2.0"
...@@ -113,7 +113,7 @@ if not tarballLocation: ...@@ -113,7 +113,7 @@ if not tarballLocation:
ret = os.system("which git") ret = os.system("which git")
if ret != 0: if ret != 0:
print "Missing git command!" print("Missing git command!")
sys.exit(1) sys.exit(1)
# Create destination directory # Create destination directory
...@@ -121,12 +121,12 @@ if not tarballLocation: ...@@ -121,12 +121,12 @@ if not tarballLocation:
basename = git_repo[pkgName].split("/")[-1] basename = git_repo[pkgName].split("/")[-1]
destDir = os.path.join("/tmp", basename) destDir = os.path.join("/tmp", basename)
if os.path.exists(destDir): if os.path.exists(destDir):
print "Deleting existing destination directory" print("Deleting existing destination directory")
subprocess.check_call(("rm -rf %s" % destDir).split()) subprocess.check_call(("rm -rf %s" % destDir).split())
# If destination directory doesn't exist, create it # If destination directory doesn't exist, create it
if not os.path.exists(destDir): if not os.path.exists(destDir):
print "Creating directory %s for git repo %s" % (destDir, git_repo[pkgName]) print("Creating directory %s for git repo %s" % (destDir, git_repo[pkgName]))
os.makedirs(destDir) os.makedirs(destDir)
# Switch to the directory # Switch to the directory
...@@ -134,46 +134,46 @@ if not tarballLocation: ...@@ -134,46 +134,46 @@ if not tarballLocation:
# If git repo already exists, reset. If not, initialize # If git repo already exists, reset. If not, initialize
if os.path.exists('.git'): if os.path.exists('.git'):
print "Resetting previously existing git repo at %s for receiving git repo %s" % (destDir, git_repo[pkgName]) print("Resetting previously existing git repo at %s for receiving git repo %s" % (destDir, git_repo[pkgName]))
subprocess.check_call("git reset --hard".split()) subprocess.check_call("git reset --hard".split())
else: else:
print "Initializing new git repo at %s for receiving git repo %s" % (destDir, git_repo[pkgName]) print("Initializing new git repo at %s for receiving git repo %s" % (destDir, git_repo[pkgName]))
subprocess.check_call("git init".split()) subprocess.check_call("git init".split())
# Fetch the contents of the repo # Fetch the contents of the repo
print "Fetching git [REP '%s' BRANCH '%s'] -> %s" % (git_repo[pkgName], branch, destDir) print("Fetching git [REP '%s' BRANCH '%s'] -> %s" % (git_repo[pkgName], branch, destDir))
subprocess.check_call(("git fetch -q -f -u -t %s %s:%s" % subprocess.check_call(("git fetch -q -f -u -t %s %s:%s" %
(git_repo[pkgName], branch, branch)).split()) (git_repo[pkgName], branch, branch)).split())
# checkout the branch specified, master by default # checkout the branch specified, master by default
print "Checking out branch %s" % branch print("Checking out branch %s" % branch)
subprocess.check_call(("git checkout %s" % branch).split()) subprocess.check_call(("git checkout %s" % branch).split())
# If a certain commit is specified, checkout that commit # If a certain commit is specified, checkout that commit
if commit is not None: if commit is not None:
print "Checking out commit %s" % commit print("Checking out commit %s" % commit)
subprocess.check_call(("git checkout %s" % commit).split()) subprocess.check_call(("git checkout %s" % commit).split())
else: else:
print "Specific commit not specified" print("Specific commit not specified")
# Adding remote origin # Adding remote origin
print "Adding remote origin" print("Adding remote origin")
args = ("git remote add origin %s" % git_repo[pkgName]).split() args = ("git remote add origin %s" % git_repo[pkgName]).split()
output = run_subprocess_cmd(args) output = run_subprocess_cmd(args)
# Get the commit and tag which repo is at # Get the commit and tag which repo is at
args = 'git log --pretty=format:%H -1'.split() args = 'git log --pretty=format:%H -1'.split()
print "Running 'git log --pretty=format:%H -1' to get top commit" print("Running 'git log --pretty=format:%H -1' to get top commit")
top_commit = run_subprocess_cmd(args) top_commit = run_subprocess_cmd(args)
args = 'git describe'.split() args = 'git describe'.split()
print "Running 'git describe' to get top tag" print("Running 'git describe' to get top tag")
top_tag = run_subprocess_cmd(args) top_tag = run_subprocess_cmd(args)
if top_tag is None: if top_tag is None:
top_tag_desc = 'no tag found' top_tag_desc = 'no tag found'
else: else:
top_tag_desc = 'tag %s' % top_tag top_tag_desc = 'tag %s' % top_tag
print "git commit ID is %s (%s)" % (top_commit, top_tag_desc) print("git commit ID is %s (%s)" % (top_commit, top_tag_desc))
# If tarball is not specified # If tarball is not specified
else: else:
...@@ -211,7 +211,7 @@ cmd = destDir + "/autogen.sh" ...@@ -211,7 +211,7 @@ cmd = destDir + "/autogen.sh"
if not os.path.exists(cmd): if not os.path.exists(cmd):
cmd = destDir + "/configure" cmd = destDir + "/configure"
if not os.path.exists(cmd): if not os.path.exists(cmd):
print "%s doesn't exist! Something's wrong!" % cmd print("%s doesn't exist! Something's wrong!" % cmd)
sys.exit(1) sys.exit(1)
if prefix is not None: if prefix is not None:
...@@ -219,10 +219,10 @@ if prefix is not None: ...@@ -219,10 +219,10 @@ if prefix is not None:
if pkgName in autogen_options.keys(): if pkgName in autogen_options.keys():
cmd += " " + autogen_options[pkgName] cmd += " " + autogen_options[pkgName]
print "Running '%s %s'" % (env_vars, cmd) print("Running '%s %s'" % (env_vars, cmd))
ret = os.system(env_vars + " " + cmd) ret = os.system(env_vars + " " + cmd)
if ret != 0: if ret != 0:
print "Return code: %s! Autogen.sh failed! Exiting!" % ret print("Return code: %s! Autogen.sh failed! Exiting!" % ret)
sys.exit(1) sys.exit(1)
# Temporary workaround for building spice-vdagent # Temporary workaround for building spice-vdagent
...@@ -232,16 +232,16 @@ if pkgName == "spice-vd-agent": ...@@ -232,16 +232,16 @@ if pkgName == "spice-vd-agent":
# Running 'make' to build and using os.system again # Running 'make' to build and using os.system again
cmd = "make" cmd = "make"
print "Running '%s %s'" % (env_vars, cmd) print("Running '%s %s'" % (env_vars, cmd))
ret = os.system("%s %s" % (env_vars, cmd)) ret = os.system("%s %s" % (env_vars, cmd))
if ret != 0: if ret != 0:
print "Return code: %s! make failed! Exiting!" % ret print("Return code: %s! make failed! Exiting!" % ret)
sys.exit(1) sys.exit(1)
# Running 'make install' to install the built libraries/binaries # Running 'make install' to install the built libraries/binaries
cmd = "make install" cmd = "make install"
print "Running '%s %s'" % (env_vars, cmd) print("Running '%s %s'" % (env_vars, cmd))
ret = os.system("%s %s" % (env_vars, cmd)) ret = os.system("%s %s" % (env_vars, cmd))
if ret != 0: if ret != 0:
print "Return code: %s! make install failed! Exiting!" % ret print("Return code: %s! make install failed! Exiting!" % ret)
sys.exit(ret) sys.exit(ret)
...@@ -167,7 +167,7 @@ def show_log_output(result_file): ...@@ -167,7 +167,7 @@ def show_log_output(result_file):
:param result_file: File which saves execution logs. :param result_file: File which saves execution logs.
""" """
with open(result_file) as fd: with open(result_file) as fd:
print os.linesep.join(fd.readlines()) print(os.linesep.join(fd.readlines()))
if __name__ == "__main__": if __name__ == "__main__":
...@@ -229,7 +229,7 @@ if __name__ == "__main__": ...@@ -229,7 +229,7 @@ if __name__ == "__main__":
verify_driver_ver(arguments.driver_path, arguments.device_name, verify_driver_ver(arguments.driver_path, arguments.device_name,
arguments.driver_name) arguments.driver_name)
elif arguments.log_output: elif arguments.log_output:
print "Execution log:\n" print("Execution log:\n")
show_log_output(result_file) show_log_output(result_file)
print "DPINST.log:\n" print("DPINST.log:\n")
show_log_output(r"C:\Windows\DPINST.log") show_log_output(r"C:\Windows\DPINST.log")
...@@ -103,7 +103,7 @@ def test(path): ...@@ -103,7 +103,7 @@ def test(path):
else: else:
vport_name = '/dev/virtio-ports/' + path vport_name = '/dev/virtio-ports/' + path
vio = VirtIoChannel(vport_name) vio = VirtIoChannel(vport_name)
print vio.read() print(vio.read())
if __name__ == "__main__": if __name__ == "__main__":
......
...@@ -42,9 +42,9 @@ class WinBufferedReadFile(object): ...@@ -42,9 +42,9 @@ class WinBufferedReadFile(object):
frags = [] frags = []
aux = 0 aux = 0
if self.verbose: if self.verbose:
print "get %s, | bufs = %s [%s]" % (n, self._n, print("get %s, | bufs = %s [%s]" % (n, self._n,
','.join(map(lambda x: str(len(x)), ','.join(map(lambda x: str(len(x)),
self._bufs))) self._bufs))))
while aux < n: while aux < n:
frags.append(self._bufs.pop(0)) frags.append(self._bufs.pop(0))
aux += len(frags[-1]) aux += len(frags[-1])
...@@ -54,9 +54,9 @@ class WinBufferedReadFile(object): ...@@ -54,9 +54,9 @@ class WinBufferedReadFile(object):
if len(rest) > 0: if len(rest) > 0:
self._bufs.append(rest) self._bufs.append(rest)
if self.verbose: if self.verbose:
print "return %s(%s), | bufs = %s [%s]" % (len(ret), n, self._n, print("return %s(%s), | bufs = %s [%s]" % (len(ret), n, self._n,
','.join(map(lambda x: str(len(x)), ','.join(map(lambda x: str(len(x)),
self._bufs))) self._bufs))))
return ret return ret
try: try:
# 4096 is the largest result viosdev will return right now. # 4096 is the largest result viosdev will return right now.
...@@ -66,9 +66,9 @@ class WinBufferedReadFile(object): ...@@ -66,9 +66,9 @@ class WinBufferedReadFile(object):
self._bufs.append(b[:nr]) self._bufs.append(b[:nr])
self._n += nr self._n += nr
if self.verbose: if self.verbose:
print "read %s, err %s | bufs = %s [%s]" % (nr, err, self._n, print("read %s, err %s | bufs = %s [%s]" % (nr, err, self._n,
','.join(map(lambda x: str(len(x)), ','.join(map(lambda x: str(len(x)),
self._bufs))) self._bufs))))
except: except:
pass pass
# Never Reached # Never Reached
......
...@@ -70,7 +70,7 @@ class GuestAgentPkg(object): ...@@ -70,7 +70,7 @@ class GuestAgentPkg(object):
if status: if status:
raise Exception("the download from %s didn't run successfully" raise Exception("the download from %s didn't run successfully"
% url) % url)
print ("\033[32m %s download successfully\033[0m" % url) print("\033[32m %s download successfully\033[0m" % url)
def parse_params(program): def parse_params(program):
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册